2021-02-04 19:15:23 +01:00
|
|
|
import log from 'loglevel';
|
|
|
|
import BigNumber from 'bignumber.js';
|
|
|
|
import abi from 'human-standard-token-abi';
|
2021-03-09 17:06:44 +01:00
|
|
|
import {
|
2021-03-18 11:20:06 +01:00
|
|
|
SWAPS_CHAINID_DEFAULT_TOKEN_MAP,
|
|
|
|
METASWAP_CHAINID_API_HOST_MAP,
|
2021-09-08 20:08:55 +02:00
|
|
|
ALLOWED_CONTRACT_ADDRESSES,
|
|
|
|
SWAPS_WRAPPED_TOKENS_ADDRESSES,
|
2021-07-09 17:24:00 +02:00
|
|
|
ETHEREUM,
|
|
|
|
POLYGON,
|
|
|
|
BSC,
|
2021-07-30 13:35:30 +02:00
|
|
|
RINKEBY,
|
2021-09-08 19:26:37 +02:00
|
|
|
SWAPS_API_V2_BASE_URL,
|
|
|
|
SWAPS_DEV_API_V2_BASE_URL,
|
|
|
|
GAS_API_BASE_URL,
|
|
|
|
GAS_DEV_API_BASE_URL,
|
2021-09-29 15:11:19 +02:00
|
|
|
SWAPS_CLIENT_ID,
|
2021-04-28 21:53:59 +02:00
|
|
|
} from '../../../shared/constants/swaps';
|
2021-07-30 13:35:30 +02:00
|
|
|
import { TRANSACTION_ENVELOPE_TYPES } from '../../../shared/constants/transaction';
|
2021-03-18 11:20:06 +01:00
|
|
|
import {
|
|
|
|
isSwapsDefaultTokenAddress,
|
|
|
|
isSwapsDefaultTokenSymbol,
|
2021-04-28 21:53:59 +02:00
|
|
|
} from '../../../shared/modules/swaps.utils';
|
2021-04-23 16:53:10 +02:00
|
|
|
import {
|
|
|
|
MAINNET_CHAIN_ID,
|
2021-07-09 17:24:00 +02:00
|
|
|
BSC_CHAIN_ID,
|
|
|
|
POLYGON_CHAIN_ID,
|
|
|
|
LOCALHOST_CHAIN_ID,
|
2021-07-30 13:35:30 +02:00
|
|
|
RINKEBY_CHAIN_ID,
|
2021-04-28 21:53:59 +02:00
|
|
|
} from '../../../shared/constants/network';
|
2021-06-10 21:27:03 +02:00
|
|
|
import { SECOND } from '../../../shared/constants/time';
|
2021-02-04 19:15:23 +01:00
|
|
|
import {
|
|
|
|
calcTokenValue,
|
|
|
|
calcTokenAmount,
|
|
|
|
} from '../../helpers/utils/token-util';
|
2020-11-03 00:41:28 +01:00
|
|
|
import {
|
|
|
|
constructTxParams,
|
|
|
|
toPrecisionWithoutTrailingZeros,
|
2021-02-04 19:15:23 +01:00
|
|
|
} from '../../helpers/utils/util';
|
2020-11-03 00:41:28 +01:00
|
|
|
import {
|
|
|
|
decimalToHex,
|
|
|
|
getValueFromWeiHex,
|
2021-02-04 19:15:23 +01:00
|
|
|
} from '../../helpers/utils/conversions.util';
|
2020-10-27 20:02:21 +01:00
|
|
|
|
2021-07-06 19:48:49 +02:00
|
|
|
import { subtractCurrencies } from '../../../shared/modules/conversion.utils';
|
2021-02-04 19:15:23 +01:00
|
|
|
import { formatCurrency } from '../../helpers/utils/confirm-tx.util';
|
|
|
|
import fetchWithCache from '../../helpers/utils/fetch-with-cache';
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
import { calcGasTotal } from '../send/send.utils';
|
2021-05-17 21:00:59 +02:00
|
|
|
import { isValidHexAddress } from '../../../shared/modules/hexstring-utils';
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const TOKEN_TRANSFER_LOG_TOPIC_HASH =
|
2021-02-04 19:15:23 +01:00
|
|
|
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-04-10 02:59:52 +02:00
|
|
|
const CACHE_REFRESH_FIVE_MINUTES = 300000;
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-09-29 15:11:19 +02:00
|
|
|
const clientIdHeader = { 'X-Client-Id': SWAPS_CLIENT_ID };
|
2021-09-20 21:06:41 +02:00
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
/**
|
|
|
|
* @param {string} type Type of an API call, e.g. "tokens"
|
|
|
|
* @param {string} chainId
|
|
|
|
* @returns string
|
|
|
|
*/
|
|
|
|
const getBaseUrlForNewSwapsApi = (type, chainId) => {
|
2021-09-08 19:26:37 +02:00
|
|
|
const useDevApis = process.env.SWAPS_USE_DEV_APIS;
|
|
|
|
const v2ApiBaseUrl = useDevApis
|
|
|
|
? SWAPS_DEV_API_V2_BASE_URL
|
|
|
|
: SWAPS_API_V2_BASE_URL;
|
|
|
|
const gasApiBaseUrl = useDevApis ? GAS_DEV_API_BASE_URL : GAS_API_BASE_URL;
|
2021-07-09 17:24:00 +02:00
|
|
|
const noNetworkSpecificTypes = ['refreshTime']; // These types don't need network info in the URL.
|
|
|
|
if (noNetworkSpecificTypes.includes(type)) {
|
2021-09-08 19:26:37 +02:00
|
|
|
return v2ApiBaseUrl;
|
2021-07-09 17:24:00 +02:00
|
|
|
}
|
|
|
|
const chainIdDecimal = chainId && parseInt(chainId, 16);
|
|
|
|
const gasApiTypes = ['gasPrices'];
|
|
|
|
if (gasApiTypes.includes(type)) {
|
2021-09-08 19:26:37 +02:00
|
|
|
return `${gasApiBaseUrl}/networks/${chainIdDecimal}`; // Gas calculations are in its own repo.
|
2021-07-09 17:24:00 +02:00
|
|
|
}
|
2021-09-08 19:26:37 +02:00
|
|
|
return `${v2ApiBaseUrl}/networks/${chainIdDecimal}`;
|
2021-07-09 17:24:00 +02:00
|
|
|
};
|
|
|
|
|
2021-09-15 15:13:18 +02:00
|
|
|
export const getBaseApi = function (
|
2021-07-09 17:24:00 +02:00
|
|
|
type,
|
|
|
|
chainId = MAINNET_CHAIN_ID,
|
|
|
|
useNewSwapsApi = false,
|
|
|
|
) {
|
|
|
|
const baseUrl = useNewSwapsApi
|
|
|
|
? getBaseUrlForNewSwapsApi(type, chainId)
|
|
|
|
: METASWAP_CHAINID_API_HOST_MAP[chainId];
|
2021-09-15 15:13:18 +02:00
|
|
|
const chainIdDecimal = chainId && parseInt(chainId, 16);
|
2021-07-20 19:17:15 +02:00
|
|
|
if (!baseUrl) {
|
|
|
|
throw new Error(`Swaps API calls are disabled for chainId: ${chainId}`);
|
|
|
|
}
|
2020-10-06 20:28:38 +02:00
|
|
|
switch (type) {
|
|
|
|
case 'trade':
|
2021-07-09 17:24:00 +02:00
|
|
|
return `${baseUrl}/trades?`;
|
2020-10-06 20:28:38 +02:00
|
|
|
case 'tokens':
|
2021-07-09 17:24:00 +02:00
|
|
|
return `${baseUrl}/tokens`;
|
2021-06-03 18:08:37 +02:00
|
|
|
case 'token':
|
2021-07-09 17:24:00 +02:00
|
|
|
return `${baseUrl}/token`;
|
2020-10-06 20:28:38 +02:00
|
|
|
case 'topAssets':
|
2021-07-09 17:24:00 +02:00
|
|
|
return `${baseUrl}/topAssets`;
|
2020-10-06 20:28:38 +02:00
|
|
|
case 'aggregatorMetadata':
|
2021-07-09 17:24:00 +02:00
|
|
|
return `${baseUrl}/aggregatorMetadata`;
|
2020-11-04 17:14:08 +01:00
|
|
|
case 'gasPrices':
|
2021-07-09 17:24:00 +02:00
|
|
|
return `${baseUrl}/gasPrices`;
|
2021-09-15 15:13:18 +02:00
|
|
|
case 'network':
|
|
|
|
// Only use v2 for this endpoint.
|
|
|
|
return `${SWAPS_API_V2_BASE_URL}/networks/${chainIdDecimal}`;
|
2020-10-06 20:28:38 +02:00
|
|
|
default:
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error('getBaseApi requires an api call type');
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const validHex = (string) => Boolean(string?.match(/^0x[a-f0-9]+$/u));
|
|
|
|
const truthyString = (string) => Boolean(string?.length);
|
2020-11-03 00:41:28 +01:00
|
|
|
const truthyDigitString = (string) =>
|
2021-02-04 19:15:23 +01:00
|
|
|
truthyString(string) && Boolean(string.match(/^\d+$/u));
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
const QUOTE_VALIDATORS = [
|
|
|
|
{
|
|
|
|
property: 'trade',
|
|
|
|
type: 'object',
|
2020-11-03 00:41:28 +01:00
|
|
|
validator: (trade) =>
|
|
|
|
trade &&
|
|
|
|
validHex(trade.data) &&
|
2021-05-17 21:00:59 +02:00
|
|
|
isValidHexAddress(trade.to, { allowNonPrefixed: false }) &&
|
|
|
|
isValidHexAddress(trade.from, { allowNonPrefixed: false }) &&
|
2020-11-03 00:41:28 +01:00
|
|
|
truthyString(trade.value),
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'approvalNeeded',
|
|
|
|
type: 'object',
|
2020-11-03 00:41:28 +01:00
|
|
|
validator: (approvalTx) =>
|
2020-10-06 20:28:38 +02:00
|
|
|
approvalTx === null ||
|
2020-11-03 00:41:28 +01:00
|
|
|
(approvalTx &&
|
2020-10-06 20:28:38 +02:00
|
|
|
validHex(approvalTx.data) &&
|
2021-05-17 21:00:59 +02:00
|
|
|
isValidHexAddress(approvalTx.to, { allowNonPrefixed: false }) &&
|
|
|
|
isValidHexAddress(approvalTx.from, { allowNonPrefixed: false })),
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'sourceAmount',
|
|
|
|
type: 'string',
|
|
|
|
validator: truthyDigitString,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'destinationAmount',
|
|
|
|
type: 'string',
|
|
|
|
validator: truthyDigitString,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'sourceToken',
|
|
|
|
type: 'string',
|
2021-05-17 21:00:59 +02:00
|
|
|
validator: (input) => isValidHexAddress(input, { allowNonPrefixed: false }),
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'destinationToken',
|
|
|
|
type: 'string',
|
2021-05-17 21:00:59 +02:00
|
|
|
validator: (input) => isValidHexAddress(input, { allowNonPrefixed: false }),
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'aggregator',
|
|
|
|
type: 'string',
|
|
|
|
validator: truthyString,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'aggType',
|
|
|
|
type: 'string',
|
|
|
|
validator: truthyString,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'error',
|
|
|
|
type: 'object',
|
|
|
|
validator: (error) => error === null || typeof error === 'object',
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'averageGas',
|
|
|
|
type: 'number',
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'maxGas',
|
|
|
|
type: 'number',
|
|
|
|
},
|
2020-12-15 18:16:51 +01:00
|
|
|
{
|
|
|
|
property: 'gasEstimate',
|
|
|
|
type: 'number|undefined',
|
|
|
|
validator: (gasEstimate) => gasEstimate === undefined || gasEstimate > 0,
|
|
|
|
},
|
2021-04-07 02:19:55 +02:00
|
|
|
{
|
|
|
|
property: 'fee',
|
|
|
|
type: 'number',
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
];
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
const TOKEN_VALIDATORS = [
|
|
|
|
{
|
|
|
|
property: 'address',
|
|
|
|
type: 'string',
|
2021-05-17 21:00:59 +02:00
|
|
|
validator: (input) => isValidHexAddress(input, { allowNonPrefixed: false }),
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'symbol',
|
|
|
|
type: 'string',
|
|
|
|
validator: (string) => truthyString(string) && string.length <= 12,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'decimals',
|
|
|
|
type: 'string|number',
|
|
|
|
validator: (string) => Number(string) >= 0 && Number(string) <= 36,
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
];
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const TOP_ASSET_VALIDATORS = TOKEN_VALIDATORS.slice(0, 2);
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
const AGGREGATOR_METADATA_VALIDATORS = [
|
|
|
|
{
|
|
|
|
property: 'color',
|
|
|
|
type: 'string',
|
|
|
|
validator: (string) => Boolean(string.match(/^#[A-Fa-f0-9]+$/u)),
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'title',
|
|
|
|
type: 'string',
|
|
|
|
validator: truthyString,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'icon',
|
|
|
|
type: 'string',
|
|
|
|
validator: (string) => Boolean(string.match(/^data:image/u)),
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
];
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-04 17:14:08 +01:00
|
|
|
const isValidDecimalNumber = (string) =>
|
2021-02-04 19:15:23 +01:00
|
|
|
!isNaN(string) && string.match(/^[.0-9]+$/u) && !isNaN(parseFloat(string));
|
2020-11-04 17:14:08 +01:00
|
|
|
|
|
|
|
const SWAP_GAS_PRICE_VALIDATOR = [
|
|
|
|
{
|
|
|
|
property: 'SafeGasPrice',
|
|
|
|
type: 'string',
|
|
|
|
validator: isValidDecimalNumber,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'ProposeGasPrice',
|
|
|
|
type: 'string',
|
|
|
|
validator: isValidDecimalNumber,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
property: 'FastGasPrice',
|
|
|
|
type: 'string',
|
|
|
|
validator: isValidDecimalNumber,
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
];
|
2020-11-04 17:14:08 +01:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
function validateData(validators, object, urlUsed) {
|
2020-10-06 20:28:38 +02:00
|
|
|
return validators.every(({ property, type, validator }) => {
|
2021-02-04 19:15:23 +01:00
|
|
|
const types = type.split('|');
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const valid =
|
|
|
|
types.some((_type) => typeof object[property] === _type) &&
|
2021-02-04 19:15:23 +01:00
|
|
|
(!validator || validator(object[property]));
|
2020-10-06 20:28:38 +02:00
|
|
|
if (!valid) {
|
2020-11-03 00:41:28 +01:00
|
|
|
log.error(
|
|
|
|
`response to GET ${urlUsed} invalid for property ${property}; value was:`,
|
|
|
|
object[property],
|
|
|
|
'| type was: ',
|
|
|
|
typeof object[property],
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return valid;
|
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2021-09-08 20:08:55 +02:00
|
|
|
export const shouldEnableDirectWrapping = (
|
|
|
|
chainId,
|
|
|
|
sourceToken,
|
|
|
|
destinationToken,
|
|
|
|
) => {
|
|
|
|
const wrappedToken = SWAPS_WRAPPED_TOKENS_ADDRESSES[chainId];
|
|
|
|
const nativeToken = SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]?.address;
|
|
|
|
return (
|
|
|
|
(sourceToken === wrappedToken && destinationToken === nativeToken) ||
|
|
|
|
(sourceToken === nativeToken && destinationToken === wrappedToken)
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2021-03-18 11:20:06 +01:00
|
|
|
export async function fetchTradesInfo(
|
|
|
|
{
|
|
|
|
slippage,
|
|
|
|
sourceToken,
|
|
|
|
sourceDecimals,
|
|
|
|
destinationToken,
|
|
|
|
value,
|
|
|
|
fromAddress,
|
|
|
|
exchangeList,
|
|
|
|
},
|
2021-07-09 17:24:00 +02:00
|
|
|
{ chainId, useNewSwapsApi },
|
2021-03-18 11:20:06 +01:00
|
|
|
) {
|
2020-10-06 20:28:38 +02:00
|
|
|
const urlParams = {
|
|
|
|
destinationToken,
|
|
|
|
sourceToken,
|
|
|
|
sourceAmount: calcTokenValue(value, sourceDecimals).toString(10),
|
|
|
|
slippage,
|
2021-06-10 21:27:03 +02:00
|
|
|
timeout: SECOND * 10,
|
2020-10-06 20:28:38 +02:00
|
|
|
walletAddress: fromAddress,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
if (exchangeList) {
|
2021-02-04 19:15:23 +01:00
|
|
|
urlParams.exchangeList = exchangeList;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-09-08 20:08:55 +02:00
|
|
|
if (shouldEnableDirectWrapping(chainId, sourceToken, destinationToken)) {
|
|
|
|
urlParams.enableDirectWrapping = true;
|
|
|
|
}
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const queryString = new URLSearchParams(urlParams).toString();
|
2021-07-09 17:24:00 +02:00
|
|
|
const tradeURL = `${getBaseApi(
|
|
|
|
'trade',
|
|
|
|
chainId,
|
|
|
|
useNewSwapsApi,
|
|
|
|
)}${queryString}`;
|
2020-11-03 00:41:28 +01:00
|
|
|
const tradesResponse = await fetchWithCache(
|
|
|
|
tradeURL,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2021-06-10 21:27:03 +02:00
|
|
|
{ cacheRefreshTime: 0, timeout: SECOND * 15 },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-10-06 20:28:38 +02:00
|
|
|
const newQuotes = tradesResponse.reduce((aggIdTradeMap, quote) => {
|
2020-11-03 00:41:28 +01:00
|
|
|
if (
|
|
|
|
quote.trade &&
|
|
|
|
!quote.error &&
|
|
|
|
validateData(QUOTE_VALIDATORS, quote, tradeURL)
|
|
|
|
) {
|
2020-10-06 20:28:38 +02:00
|
|
|
const constructedTrade = constructTxParams({
|
|
|
|
to: quote.trade.to,
|
|
|
|
from: quote.trade.from,
|
|
|
|
data: quote.trade.data,
|
|
|
|
amount: decimalToHex(quote.trade.value),
|
|
|
|
gas: decimalToHex(quote.maxGas),
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
let { approvalNeeded } = quote;
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
if (approvalNeeded) {
|
|
|
|
approvalNeeded = constructTxParams({
|
|
|
|
...approvalNeeded,
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...aggIdTradeMap,
|
|
|
|
[quote.aggregator]: {
|
|
|
|
...quote,
|
|
|
|
slippage,
|
|
|
|
trade: constructedTrade,
|
|
|
|
approvalNeeded,
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return aggIdTradeMap;
|
|
|
|
}, {});
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
return newQuotes;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
export async function fetchToken(contractAddress, chainId, useNewSwapsApi) {
|
|
|
|
const tokenUrl = getBaseApi('token', chainId, useNewSwapsApi);
|
2021-06-03 18:08:37 +02:00
|
|
|
const token = await fetchWithCache(
|
|
|
|
`${tokenUrl}?address=${contractAddress}`,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2021-06-03 18:08:37 +02:00
|
|
|
{ cacheRefreshTime: CACHE_REFRESH_FIVE_MINUTES },
|
|
|
|
);
|
|
|
|
return token;
|
|
|
|
}
|
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
export async function fetchTokens(chainId, useNewSwapsApi) {
|
|
|
|
const tokensUrl = getBaseApi('tokens', chainId, useNewSwapsApi);
|
2020-11-03 00:41:28 +01:00
|
|
|
const tokens = await fetchWithCache(
|
2021-06-03 18:08:37 +02:00
|
|
|
tokensUrl,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2021-04-10 02:59:52 +02:00
|
|
|
{ cacheRefreshTime: CACHE_REFRESH_FIVE_MINUTES },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2021-03-15 17:51:43 +01:00
|
|
|
const filteredTokens = [
|
2021-03-18 11:20:06 +01:00
|
|
|
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId],
|
2021-03-15 17:51:43 +01:00
|
|
|
...tokens.filter((token) => {
|
|
|
|
return (
|
2021-06-03 18:08:37 +02:00
|
|
|
validateData(TOKEN_VALIDATORS, token, tokensUrl) &&
|
2021-03-15 17:51:43 +01:00
|
|
|
!(
|
2021-03-18 11:20:06 +01:00
|
|
|
isSwapsDefaultTokenSymbol(token.symbol, chainId) ||
|
|
|
|
isSwapsDefaultTokenAddress(token.address, chainId)
|
2021-03-15 17:51:43 +01:00
|
|
|
)
|
|
|
|
);
|
|
|
|
}),
|
|
|
|
];
|
2021-02-04 19:15:23 +01:00
|
|
|
return filteredTokens;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
export async function fetchAggregatorMetadata(chainId, useNewSwapsApi) {
|
|
|
|
const aggregatorMetadataUrl = getBaseApi(
|
|
|
|
'aggregatorMetadata',
|
|
|
|
chainId,
|
|
|
|
useNewSwapsApi,
|
|
|
|
);
|
2020-11-03 00:41:28 +01:00
|
|
|
const aggregators = await fetchWithCache(
|
|
|
|
aggregatorMetadataUrl,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2021-04-10 02:59:52 +02:00
|
|
|
{ cacheRefreshTime: CACHE_REFRESH_FIVE_MINUTES },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
|
|
|
const filteredAggregators = {};
|
2020-10-06 20:28:38 +02:00
|
|
|
for (const aggKey in aggregators) {
|
2020-11-03 00:41:28 +01:00
|
|
|
if (
|
|
|
|
validateData(
|
|
|
|
AGGREGATOR_METADATA_VALIDATORS,
|
|
|
|
aggregators[aggKey],
|
|
|
|
aggregatorMetadataUrl,
|
|
|
|
)
|
|
|
|
) {
|
2021-02-04 19:15:23 +01:00
|
|
|
filteredAggregators[aggKey] = aggregators[aggKey];
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return filteredAggregators;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
export async function fetchTopAssets(chainId, useNewSwapsApi) {
|
|
|
|
const topAssetsUrl = getBaseApi('topAssets', chainId, useNewSwapsApi);
|
2020-11-03 00:41:28 +01:00
|
|
|
const response = await fetchWithCache(
|
|
|
|
topAssetsUrl,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2021-04-10 02:59:52 +02:00
|
|
|
{ cacheRefreshTime: CACHE_REFRESH_FIVE_MINUTES },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-10-06 20:28:38 +02:00
|
|
|
const topAssetsMap = response.reduce((_topAssetsMap, asset, index) => {
|
|
|
|
if (validateData(TOP_ASSET_VALIDATORS, asset, topAssetsUrl)) {
|
2021-02-04 19:15:23 +01:00
|
|
|
return { ..._topAssetsMap, [asset.address]: { index: String(index) } };
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return _topAssetsMap;
|
|
|
|
}, {});
|
|
|
|
return topAssetsMap;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
export async function fetchSwapsFeatureFlags() {
|
2021-09-08 19:26:37 +02:00
|
|
|
const v2ApiBaseUrl = process.env.SWAPS_USE_DEV_APIS
|
|
|
|
? SWAPS_DEV_API_V2_BASE_URL
|
|
|
|
: SWAPS_API_V2_BASE_URL;
|
2021-07-09 17:24:00 +02:00
|
|
|
const response = await fetchWithCache(
|
2021-09-08 19:26:37 +02:00
|
|
|
`${v2ApiBaseUrl}/featureFlags`,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2020-11-03 00:41:28 +01:00
|
|
|
{ cacheRefreshTime: 600000 },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2021-07-09 17:24:00 +02:00
|
|
|
return response;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export async function fetchTokenPrice(address) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const query = `contract_addresses=${address}&vs_currencies=eth`;
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const prices = await fetchWithCache(
|
|
|
|
`https://api.coingecko.com/api/v3/simple/token_price/ethereum?${query}`,
|
|
|
|
{ method: 'GET' },
|
|
|
|
{ cacheRefreshTime: 60000 },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
|
|
|
return prices && prices[address]?.eth;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export async function fetchTokenBalance(address, userAddress) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const tokenContract = global.eth.contract(abi).at(address);
|
2020-10-06 20:28:38 +02:00
|
|
|
const tokenBalancePromise = tokenContract
|
|
|
|
? tokenContract.balanceOf(userAddress)
|
2021-02-04 19:15:23 +01:00
|
|
|
: Promise.resolve();
|
|
|
|
const usersToken = await tokenBalancePromise;
|
|
|
|
return usersToken;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2021-07-09 17:24:00 +02:00
|
|
|
export async function fetchSwapsGasPrices(chainId, useNewSwapsApi) {
|
|
|
|
const gasPricesUrl = getBaseApi('gasPrices', chainId, useNewSwapsApi);
|
2020-11-04 17:14:08 +01:00
|
|
|
const response = await fetchWithCache(
|
|
|
|
gasPricesUrl,
|
2021-09-20 21:06:41 +02:00
|
|
|
{ method: 'GET', headers: clientIdHeader },
|
2021-03-28 15:18:44 +02:00
|
|
|
{ cacheRefreshTime: 30000 },
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-11-04 17:14:08 +01:00
|
|
|
const responseIsValid = validateData(
|
|
|
|
SWAP_GAS_PRICE_VALIDATOR,
|
|
|
|
response,
|
|
|
|
gasPricesUrl,
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-11-04 17:14:08 +01:00
|
|
|
|
|
|
|
if (!responseIsValid) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error(`${gasPricesUrl} response is invalid`);
|
2020-11-04 17:14:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const {
|
|
|
|
SafeGasPrice: safeLow,
|
|
|
|
ProposeGasPrice: average,
|
|
|
|
FastGasPrice: fast,
|
2021-02-04 19:15:23 +01:00
|
|
|
} = response;
|
2020-11-04 17:14:08 +01:00
|
|
|
|
|
|
|
return {
|
|
|
|
safeLow,
|
|
|
|
average,
|
|
|
|
fast,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-11-04 17:14:08 +01:00
|
|
|
}
|
|
|
|
|
2021-03-18 11:20:06 +01:00
|
|
|
export function getRenderableNetworkFeesForQuote({
|
2020-10-27 20:02:21 +01:00
|
|
|
tradeGas,
|
|
|
|
approveGas,
|
|
|
|
gasPrice,
|
|
|
|
currentCurrency,
|
|
|
|
conversionRate,
|
|
|
|
tradeValue,
|
|
|
|
sourceSymbol,
|
|
|
|
sourceAmount,
|
2021-03-18 11:20:06 +01:00
|
|
|
chainId,
|
2021-03-29 21:30:06 +02:00
|
|
|
nativeCurrencySymbol,
|
2021-03-18 11:20:06 +01:00
|
|
|
}) {
|
2020-11-03 00:41:28 +01:00
|
|
|
const totalGasLimitForCalculation = new BigNumber(tradeGas || '0x0', 16)
|
|
|
|
.plus(approveGas || '0x0', 16)
|
2021-02-04 19:15:23 +01:00
|
|
|
.toString(16);
|
|
|
|
const gasTotalInWeiHex = calcGasTotal(totalGasLimitForCalculation, gasPrice);
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-10-27 20:02:21 +01:00
|
|
|
const nonGasFee = new BigNumber(tradeValue, 16)
|
2021-03-18 11:20:06 +01:00
|
|
|
.minus(
|
|
|
|
isSwapsDefaultTokenSymbol(sourceSymbol, chainId) ? sourceAmount : 0,
|
|
|
|
10,
|
|
|
|
)
|
2021-02-04 19:15:23 +01:00
|
|
|
.toString(16);
|
2020-10-27 20:02:21 +01:00
|
|
|
|
|
|
|
const totalWeiCost = new BigNumber(gasTotalInWeiHex, 16)
|
|
|
|
.plus(nonGasFee, 16)
|
2021-02-04 19:15:23 +01:00
|
|
|
.toString(16);
|
2020-10-27 20:02:21 +01:00
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
const ethFee = getValueFromWeiHex({
|
2020-10-27 20:02:21 +01:00
|
|
|
value: totalWeiCost,
|
2020-10-06 20:28:38 +02:00
|
|
|
toDenomination: 'ETH',
|
2020-10-20 01:29:31 +02:00
|
|
|
numberOfDecimals: 5,
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
const rawNetworkFees = getValueFromWeiHex({
|
2020-10-27 20:02:21 +01:00
|
|
|
value: totalWeiCost,
|
2020-10-06 20:28:38 +02:00
|
|
|
toCurrency: currentCurrency,
|
|
|
|
conversionRate,
|
|
|
|
numberOfDecimals: 2,
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
|
|
|
const formattedNetworkFee = formatCurrency(rawNetworkFees, currentCurrency);
|
2021-03-29 21:30:06 +02:00
|
|
|
|
|
|
|
const chainCurrencySymbolToUse =
|
|
|
|
nativeCurrencySymbol || SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId].symbol;
|
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
return {
|
|
|
|
rawNetworkFees,
|
|
|
|
rawEthFee: ethFee,
|
|
|
|
feeInFiat: formattedNetworkFee,
|
2021-03-29 21:30:06 +02:00
|
|
|
feeInEth: `${ethFee} ${chainCurrencySymbolToUse}`,
|
2020-10-27 20:02:21 +01:00
|
|
|
nonGasFee,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export function quotesToRenderableData(
|
|
|
|
quotes,
|
|
|
|
gasPrice,
|
|
|
|
conversionRate,
|
|
|
|
currentCurrency,
|
|
|
|
approveGas,
|
|
|
|
tokenConversionRates,
|
2021-03-18 11:20:06 +01:00
|
|
|
chainId,
|
2020-11-03 00:41:28 +01:00
|
|
|
) {
|
2020-10-06 20:28:38 +02:00
|
|
|
return Object.values(quotes).map((quote) => {
|
2020-10-22 16:58:19 +02:00
|
|
|
const {
|
|
|
|
destinationAmount = 0,
|
|
|
|
sourceAmount = 0,
|
|
|
|
sourceTokenInfo,
|
|
|
|
destinationTokenInfo,
|
|
|
|
slippage,
|
|
|
|
aggType,
|
|
|
|
aggregator,
|
|
|
|
gasEstimateWithRefund,
|
|
|
|
averageGas,
|
|
|
|
fee,
|
2020-10-27 20:02:21 +01:00
|
|
|
trade,
|
2021-02-04 19:15:23 +01:00
|
|
|
} = quote;
|
2020-11-03 00:41:28 +01:00
|
|
|
const sourceValue = calcTokenAmount(
|
|
|
|
sourceAmount,
|
2021-01-19 18:05:58 +01:00
|
|
|
sourceTokenInfo.decimals,
|
2021-02-04 19:15:23 +01:00
|
|
|
).toString(10);
|
2020-11-03 00:41:28 +01:00
|
|
|
const destinationValue = calcTokenAmount(
|
|
|
|
destinationAmount,
|
2021-01-19 18:05:58 +01:00
|
|
|
destinationTokenInfo.decimals,
|
2021-02-04 19:15:23 +01:00
|
|
|
).toPrecision(8);
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
const {
|
|
|
|
feeInFiat,
|
|
|
|
rawNetworkFees,
|
|
|
|
rawEthFee,
|
|
|
|
feeInEth,
|
2021-03-18 11:20:06 +01:00
|
|
|
} = getRenderableNetworkFeesForQuote({
|
|
|
|
tradeGas: gasEstimateWithRefund || decimalToHex(averageGas || 800000),
|
2020-10-06 20:28:38 +02:00
|
|
|
approveGas,
|
|
|
|
gasPrice,
|
|
|
|
currentCurrency,
|
|
|
|
conversionRate,
|
2021-03-18 11:20:06 +01:00
|
|
|
tradeValue: trade.value,
|
|
|
|
sourceSymbol: sourceTokenInfo.symbol,
|
2020-10-27 20:02:21 +01:00
|
|
|
sourceAmount,
|
2021-03-18 11:20:06 +01:00
|
|
|
chainId,
|
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const slippageMultiplier = new BigNumber(100 - slippage).div(100);
|
2020-11-03 00:41:28 +01:00
|
|
|
const minimumAmountReceived = new BigNumber(destinationValue)
|
|
|
|
.times(slippageMultiplier)
|
2021-02-04 19:15:23 +01:00
|
|
|
.toFixed(6);
|
2020-11-03 00:41:28 +01:00
|
|
|
|
|
|
|
const tokenConversionRate =
|
2021-02-04 19:15:23 +01:00
|
|
|
tokenConversionRates[destinationTokenInfo.address];
|
2021-03-18 11:20:06 +01:00
|
|
|
const ethValueOfTrade = isSwapsDefaultTokenSymbol(
|
|
|
|
destinationTokenInfo.symbol,
|
|
|
|
chainId,
|
|
|
|
)
|
|
|
|
? calcTokenAmount(destinationAmount, destinationTokenInfo.decimals).minus(
|
|
|
|
rawEthFee,
|
|
|
|
10,
|
|
|
|
)
|
|
|
|
: new BigNumber(tokenConversionRate || 0, 10)
|
|
|
|
.times(
|
|
|
|
calcTokenAmount(destinationAmount, destinationTokenInfo.decimals),
|
|
|
|
10,
|
|
|
|
)
|
|
|
|
.minus(rawEthFee, 10);
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
let liquiditySourceKey;
|
|
|
|
let renderedSlippage = slippage;
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
if (aggType === 'AGG') {
|
2021-02-04 19:15:23 +01:00
|
|
|
liquiditySourceKey = 'swapAggregator';
|
2020-10-06 20:28:38 +02:00
|
|
|
} else if (aggType === 'RFQ') {
|
2021-02-04 19:15:23 +01:00
|
|
|
liquiditySourceKey = 'swapRequestForQuotation';
|
|
|
|
renderedSlippage = 0;
|
2020-10-06 20:28:38 +02:00
|
|
|
} else if (aggType === 'DEX') {
|
2021-02-04 19:15:23 +01:00
|
|
|
liquiditySourceKey = 'swapDecentralizedExchange';
|
2021-09-08 20:08:55 +02:00
|
|
|
} else if (aggType === 'CONTRACT') {
|
|
|
|
liquiditySourceKey = 'swapDirectContract';
|
2020-10-06 20:28:38 +02:00
|
|
|
} else {
|
2021-02-04 19:15:23 +01:00
|
|
|
liquiditySourceKey = 'swapUnknown';
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
aggId: aggregator,
|
|
|
|
amountReceiving: `${destinationValue} ${destinationTokenInfo.symbol}`,
|
|
|
|
destinationTokenDecimals: destinationTokenInfo.decimals,
|
|
|
|
destinationTokenSymbol: destinationTokenInfo.symbol,
|
2020-10-07 02:37:38 +02:00
|
|
|
destinationTokenValue: formatSwapsValueForDisplay(destinationValue),
|
2020-12-08 17:47:53 +01:00
|
|
|
destinationIconUrl: destinationTokenInfo.iconUrl,
|
2020-10-06 20:28:38 +02:00
|
|
|
isBestQuote: quote.isBestQuote,
|
|
|
|
liquiditySourceKey,
|
|
|
|
feeInEth,
|
|
|
|
detailedNetworkFees: `${feeInEth} (${feeInFiat})`,
|
|
|
|
networkFees: feeInFiat,
|
|
|
|
quoteSource: aggType,
|
|
|
|
rawNetworkFees,
|
|
|
|
slippage: renderedSlippage,
|
|
|
|
sourceTokenDecimals: sourceTokenInfo.decimals,
|
|
|
|
sourceTokenSymbol: sourceTokenInfo.symbol,
|
|
|
|
sourceTokenValue: sourceValue,
|
2020-12-08 17:47:53 +01:00
|
|
|
sourceTokenIconUrl: sourceTokenInfo.iconUrl,
|
2020-10-06 20:28:38 +02:00
|
|
|
ethValueOfTrade,
|
|
|
|
minimumAmountReceived,
|
2020-10-22 16:58:19 +02:00
|
|
|
metaMaskFee: fee,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export function getSwapsTokensReceivedFromTxMeta(
|
|
|
|
tokenSymbol,
|
|
|
|
txMeta,
|
|
|
|
tokenAddress,
|
|
|
|
accountAddress,
|
|
|
|
tokenDecimals,
|
|
|
|
approvalTxMeta,
|
2021-03-18 11:20:06 +01:00
|
|
|
chainId,
|
2020-11-03 00:41:28 +01:00
|
|
|
) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const txReceipt = txMeta?.txReceipt;
|
2021-08-03 00:52:18 +02:00
|
|
|
const networkAndAccountSupports1559 =
|
2021-07-30 13:35:30 +02:00
|
|
|
txMeta?.txReceipt?.type === TRANSACTION_ENVELOPE_TYPES.FEE_MARKET;
|
2021-03-18 11:20:06 +01:00
|
|
|
if (isSwapsDefaultTokenSymbol(tokenSymbol, chainId)) {
|
2020-11-03 00:41:28 +01:00
|
|
|
if (
|
|
|
|
!txReceipt ||
|
|
|
|
!txMeta ||
|
|
|
|
!txMeta.postTxBalance ||
|
|
|
|
!txMeta.preTxBalance
|
|
|
|
) {
|
2021-02-04 19:15:23 +01:00
|
|
|
return null;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2020-10-12 21:56:53 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
let approvalTxGasCost = '0x0';
|
2020-10-12 21:56:53 +02:00
|
|
|
if (approvalTxMeta && approvalTxMeta.txReceipt) {
|
2020-11-03 00:41:28 +01:00
|
|
|
approvalTxGasCost = calcGasTotal(
|
|
|
|
approvalTxMeta.txReceipt.gasUsed,
|
2021-08-03 00:52:18 +02:00
|
|
|
networkAndAccountSupports1559
|
2021-07-30 13:35:30 +02:00
|
|
|
? approvalTxMeta.txReceipt.effectiveGasPrice // Base fee + priority fee.
|
|
|
|
: approvalTxMeta.txParams.gasPrice,
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-10-12 21:56:53 +02:00
|
|
|
}
|
|
|
|
|
2021-07-30 13:35:30 +02:00
|
|
|
const gasCost = calcGasTotal(
|
|
|
|
txReceipt.gasUsed,
|
2021-08-03 00:52:18 +02:00
|
|
|
networkAndAccountSupports1559
|
|
|
|
? txReceipt.effectiveGasPrice
|
|
|
|
: txMeta.txParams.gasPrice,
|
2021-07-30 13:35:30 +02:00
|
|
|
);
|
2020-11-03 00:41:28 +01:00
|
|
|
const totalGasCost = new BigNumber(gasCost, 16)
|
|
|
|
.plus(approvalTxGasCost, 16)
|
2021-02-04 19:15:23 +01:00
|
|
|
.toString(16);
|
2020-11-03 00:41:28 +01:00
|
|
|
|
|
|
|
const preTxBalanceLessGasCost = subtractCurrencies(
|
|
|
|
txMeta.preTxBalance,
|
|
|
|
totalGasCost,
|
|
|
|
{
|
|
|
|
aBase: 16,
|
|
|
|
bBase: 16,
|
|
|
|
toNumericBase: 'hex',
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
2020-10-12 21:56:53 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const ethReceived = subtractCurrencies(
|
|
|
|
txMeta.postTxBalance,
|
|
|
|
preTxBalanceLessGasCost,
|
|
|
|
{
|
|
|
|
aBase: 16,
|
|
|
|
bBase: 16,
|
|
|
|
fromDenomination: 'WEI',
|
|
|
|
toDenomination: 'ETH',
|
|
|
|
toNumericBase: 'dec',
|
|
|
|
numberOfDecimals: 6,
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
|
|
|
return ethReceived;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
const txReceiptLogs = txReceipt?.logs;
|
2020-10-06 20:28:38 +02:00
|
|
|
if (txReceiptLogs && txReceipt?.status !== '0x0') {
|
|
|
|
const tokenTransferLog = txReceiptLogs.find((txReceiptLog) => {
|
2020-11-03 00:41:28 +01:00
|
|
|
const isTokenTransfer =
|
|
|
|
txReceiptLog.topics &&
|
2021-02-04 19:15:23 +01:00
|
|
|
txReceiptLog.topics[0] === TOKEN_TRANSFER_LOG_TOPIC_HASH;
|
|
|
|
const isTransferFromGivenToken = txReceiptLog.address === tokenAddress;
|
2020-11-03 00:41:28 +01:00
|
|
|
const isTransferFromGivenAddress =
|
|
|
|
txReceiptLog.topics &&
|
|
|
|
txReceiptLog.topics[2] &&
|
2021-02-04 19:15:23 +01:00
|
|
|
txReceiptLog.topics[2].match(accountAddress.slice(2));
|
2020-11-03 00:41:28 +01:00
|
|
|
return (
|
|
|
|
isTokenTransfer &&
|
|
|
|
isTransferFromGivenToken &&
|
|
|
|
isTransferFromGivenAddress
|
2021-02-04 19:15:23 +01:00
|
|
|
);
|
|
|
|
});
|
2020-10-06 20:28:38 +02:00
|
|
|
return tokenTransferLog
|
|
|
|
? toPrecisionWithoutTrailingZeros(
|
2020-11-03 00:41:28 +01:00
|
|
|
calcTokenAmount(tokenTransferLog.data, tokenDecimals).toString(10),
|
|
|
|
6,
|
|
|
|
)
|
2021-02-04 19:15:23 +01:00
|
|
|
: '';
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return null;
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2020-10-07 02:37:38 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export function formatSwapsValueForDisplay(destinationAmount) {
|
2021-02-04 19:15:23 +01:00
|
|
|
let amountToDisplay = toPrecisionWithoutTrailingZeros(destinationAmount, 12);
|
2020-10-07 02:37:38 +02:00
|
|
|
if (amountToDisplay.match(/e[+-]/u)) {
|
2021-02-04 19:15:23 +01:00
|
|
|
amountToDisplay = new BigNumber(amountToDisplay).toFixed();
|
2020-10-07 02:37:38 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return amountToDisplay;
|
2020-10-07 02:37:38 +02:00
|
|
|
}
|
2021-04-23 16:53:10 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks whether a contract address is valid before swapping tokens.
|
|
|
|
*
|
|
|
|
* @param {string} contractAddress - E.g. "0x881d40237659c251811cec9c364ef91dc08d300c" for mainnet
|
|
|
|
* @param {object} swapMetaData - We check the following 2 fields, e.g. { token_from: "ETH", token_to: "WETH" }
|
|
|
|
* @param {string} chainId - The hex encoded chain ID to check
|
|
|
|
* @returns {boolean} Whether a contract address is valid or not
|
|
|
|
*/
|
|
|
|
export const isContractAddressValid = (
|
|
|
|
contractAddress,
|
|
|
|
chainId = MAINNET_CHAIN_ID,
|
|
|
|
) => {
|
2021-09-08 20:08:55 +02:00
|
|
|
if (!contractAddress || !ALLOWED_CONTRACT_ADDRESSES[chainId]) {
|
2021-04-23 16:53:10 +02:00
|
|
|
return false;
|
|
|
|
}
|
2021-09-08 20:08:55 +02:00
|
|
|
return ALLOWED_CONTRACT_ADDRESSES[chainId].some(
|
2021-04-23 16:53:10 +02:00
|
|
|
// Sometimes we get a contract address with a few upper-case chars and since addresses are
|
2021-09-08 20:08:55 +02:00
|
|
|
// case-insensitive, we compare lowercase versions for validity.
|
|
|
|
(allowedContractAddress) =>
|
|
|
|
contractAddress.toLowerCase() === allowedContractAddress.toLowerCase(),
|
2021-04-23 16:53:10 +02:00
|
|
|
);
|
|
|
|
};
|
2021-07-09 17:24:00 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} chainId
|
|
|
|
* @returns string e.g. ethereum, bsc or polygon
|
|
|
|
*/
|
|
|
|
export const getNetworkNameByChainId = (chainId) => {
|
|
|
|
switch (chainId) {
|
|
|
|
case MAINNET_CHAIN_ID:
|
|
|
|
return ETHEREUM;
|
|
|
|
case BSC_CHAIN_ID:
|
|
|
|
return BSC;
|
|
|
|
case POLYGON_CHAIN_ID:
|
|
|
|
return POLYGON;
|
2021-07-30 13:35:30 +02:00
|
|
|
case RINKEBY_CHAIN_ID:
|
|
|
|
return RINKEBY;
|
2021-07-09 17:24:00 +02:00
|
|
|
default:
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* It returns info about if Swaps are enabled and if we should use our new APIs for it.
|
|
|
|
* @param {object} swapsFeatureFlags
|
|
|
|
* @param {string} chainId
|
|
|
|
* @returns object with 2 items: "swapsFeatureIsLive" and "useNewSwapsApi"
|
|
|
|
*/
|
|
|
|
export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => {
|
|
|
|
const networkName = getNetworkNameByChainId(chainId);
|
2021-07-30 13:35:30 +02:00
|
|
|
// Use old APIs for testnet and Rinkeby.
|
|
|
|
if ([LOCALHOST_CHAIN_ID, RINKEBY_CHAIN_ID].includes(chainId)) {
|
2021-07-09 17:24:00 +02:00
|
|
|
return {
|
|
|
|
swapsFeatureIsLive: true,
|
|
|
|
useNewSwapsApi: false,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
// If a network name is not found in the list of feature flags, disable Swaps.
|
|
|
|
if (!swapsFeatureFlags[networkName]) {
|
|
|
|
return {
|
|
|
|
swapsFeatureIsLive: false,
|
|
|
|
useNewSwapsApi: false,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
const isNetworkEnabledForNewApi =
|
|
|
|
swapsFeatureFlags[networkName].extension_active;
|
|
|
|
if (isNetworkEnabledForNewApi) {
|
|
|
|
return {
|
|
|
|
swapsFeatureIsLive: true,
|
|
|
|
useNewSwapsApi: true,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
swapsFeatureIsLive: swapsFeatureFlags[networkName].fallback_to_v1,
|
|
|
|
useNewSwapsApi: false,
|
|
|
|
};
|
|
|
|
};
|
2021-07-22 19:29:31 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {number} value
|
|
|
|
* @returns number
|
|
|
|
*/
|
|
|
|
export const countDecimals = (value) => {
|
|
|
|
if (!value || Math.floor(value) === value) return 0;
|
|
|
|
return value.toString().split('.')[1]?.length || 0;
|
|
|
|
};
|