Skip to content

Commit

Permalink
Swaps: Use quotes conversion rate (#2795)
Browse files Browse the repository at this point in the history
  • Loading branch information
wachunei authored Jul 27, 2021
1 parent 5d3a5a7 commit d5d62ab
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 65 deletions.
58 changes: 25 additions & 33 deletions app/components/UI/Swaps/QuotesView.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import {
weiToFiat
} from '../../../util/number';
import { isMainNet, isMainnetByChainId } from '../../../util/networks';
import { safeToChecksumAddress } from '../../../util/address';
import { getErrorMessage, getFetchParams, getQuotesNavigationsParams, isSwapsNativeAsset } from './utils';
import { colors } from '../../../styles/common';
import { strings } from '../../../../locales/i18n';
Expand Down Expand Up @@ -224,32 +223,14 @@ async function resetAndStartPolling({ slippage, sourceToken, destinationToken, s
if (!sourceToken || !destinationToken) {
return;
}
const { SwapsController, TokenRatesController, TokensController } = Engine.context;
const contractExchangeRates = TokenRatesController.state.contractExchangeRates;
// ff the token is not in the wallet, we'll add it
if (
!isSwapsNativeAsset(destinationToken) &&
!(safeToChecksumAddress(destinationToken.address) in contractExchangeRates)
) {
const { address, symbol, decimals } = destinationToken;
await TokensController.addToken(address, symbol, decimals);
await new Promise(resolve =>
setTimeout(() => {
resolve();
}, 500)
);
}
const destinationTokenConversionRate =
TokenRatesController.state.contractExchangeRates[safeToChecksumAddress(destinationToken.address)] || 0;
const { SwapsController } = Engine.context;

// TODO: destinationToken could be the 0 address for ETH, also tokens that aren't on the wallet
const fetchParams = getFetchParams({
slippage,
sourceToken,
destinationToken,
sourceAmount,
walletAddress,
destinationTokenConversionRate
walletAddress
});
await SwapsController.stopPollingAndResetState();
await SwapsController.startFetchAndSetQuotes(fetchParams, fetchParams.metaData);
Expand All @@ -265,6 +246,17 @@ const gasLimitWithMultiplier = (gasLimit, multiplier) => {
return new BigNumber(gasLimit).times(multiplier).integerValue();
};

async function addTokenToAssetsController(newToken) {
const { TokensController } = Engine.context;
if (
!isSwapsNativeAsset(newToken) &&
!TokensController.state.tokens.includes(token => toLowerCaseEquals(token.address, newToken.address))
) {
const { address, symbol, decimals } = newToken;
await TokensController.addToken(address, symbol, decimals);
}
}

function SwapsQuotesView({
swapsTokens,
accounts,
Expand Down Expand Up @@ -301,15 +293,6 @@ function SwapsQuotesView({
toLowerCaseEquals(token.address, destinationTokenAddress)
);

const hasConversionRate =
Boolean(destinationToken) &&
(isSwapsNativeAsset(destinationToken) ||
Boolean(
Engine.context.TokenRatesController.state.contractExchangeRates?.[
safeToChecksumAddress(destinationToken.address)
]
));

/* State */
const [firstLoadTime, setFirstLoadTime] = useState(Date.now());
const [isFirstLoad, setIsFirstLoad] = useState(true);
Expand Down Expand Up @@ -339,6 +322,14 @@ function SwapsQuotesView({
const [isSaving] = useState(false);
const [isInFetch, setIsInFetch] = useState(false);

const hasConversionRate = useMemo(
() =>
Boolean(destinationToken) &&
(isSwapsNativeAsset(destinationToken) ||
(Object.keys(quotes).length > 0 && (Object.values(quotes)[0]?.destinationTokenRate ?? null) !== null)),
[destinationToken, quotes]
);

/* Get quotes as an array sorted by overallValue */
const allQuotes = useMemo(() => {
if (!quotes || !quoteValues || Object.keys(quotes).length === 0 || Object.keys(quoteValues).length === 0) {
Expand Down Expand Up @@ -573,7 +564,6 @@ function SwapsQuotesView({
});

const { TransactionController } = Engine.context;

const newSwapsTransactions = TransactionController.state.swapsTransactions || {};
let approvalTransactionMetaId;
if (approvalTransaction) {
Expand Down Expand Up @@ -605,6 +595,8 @@ function SwapsQuotesView({
WalletDevice.MM_MOBILE
);
updateSwapsTransactions(transactionMeta, approvalTransactionMetaId, newSwapsTransactions);
await addTokenToAssetsController(destinationToken);
await addTokenToAssetsController(sourceToken);
} catch (e) {
// send analytics
}
Expand Down Expand Up @@ -1317,7 +1309,7 @@ function SwapsQuotesView({
toWei(selectedQuoteValue?.ethFee),
conversionRate,
currentCurrency
)}`}
) || ''}`}
</Text>
</View>
</View>
Expand All @@ -1343,7 +1335,7 @@ function SwapsQuotesView({
toWei(selectedQuoteValue?.maxEthFee),
conversionRate,
currentCurrency
)}`}
) || ''}`}
</Text>
</View>
</View>
Expand Down
14 changes: 2 additions & 12 deletions app/components/UI/Swaps/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,26 +85,16 @@ export function getQuotesNavigationsParams(route) {
* @param {string} sourceAmount Amount in minimal token units of sourceToken to be swapped
* @param {string} fromAddress Current address attempting to swap
*/
export function getFetchParams({
slippage = 1,
sourceToken,
destinationToken,
sourceAmount,
walletAddress,
destinationTokenConversionRate
}) {
export function getFetchParams({ slippage = 1, sourceToken, destinationToken, sourceAmount, walletAddress }) {
return {
slippage,
sourceToken: sourceToken.address,
destinationToken: destinationToken.address,
sourceAmount,
walletAddress,
balanceError: undefined,
metaData: {
sourceTokenInfo: sourceToken,
destinationTokenInfo: destinationToken,
accountBalance: '0x0',
destinationTokenConversionRate
destinationTokenInfo: destinationToken
}
};
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
"@metamask/contract-metadata": "^1.23.0",
"@metamask/controllers": "13.1.0",
"@metamask/etherscan-link": "^2.0.0",
"@metamask/swaps-controller": "^4.0.0",
"@metamask/swaps-controller": "^4.1.0",
"@react-native-community/async-storage": "1.12.1",
"@react-native-community/blur": "^3.6.0",
"@react-native-community/checkbox": "^0.4.2",
Expand Down
36 changes: 17 additions & 19 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1433,11 +1433,6 @@
resolved "https://registry.yarnpkg.com/@metamask/contract-metadata/-/contract-metadata-1.23.0.tgz#c70be7f3eaeeb791651ce793b7cdc230e9780b18"
integrity sha512-oTUqL9dtXtbng60DZMRsBmZ5HiOUUfEsZjuswOJ0yHO24YsW0ktCcgCJVYPv1HcOsF0SVrRtG4rtrvOl4nY+HA==

"@metamask/contract-metadata@^1.24.0":
version "1.25.0"
resolved "https://registry.yarnpkg.com/@metamask/contract-metadata/-/contract-metadata-1.25.0.tgz#442ace91fb40165310764b68d8096d0017bb0492"
integrity sha512-yhmYB9CQPv0dckNcPoWDcgtrdUp0OgK0uvkRE5QIBv4b3qENI1/03BztvK2ijbTuMlORUpjPq7/1MQDUPoRPVw==

"@metamask/contract-metadata@^1.27.0":
version "1.27.0"
resolved "https://registry.yarnpkg.com/@metamask/contract-metadata/-/contract-metadata-1.27.0.tgz#1e65b821bad6f7d8313dd881116e4366b0662f75"
Expand Down Expand Up @@ -1479,33 +1474,36 @@
web3 "^0.20.7"
web3-provider-engine "^16.0.1"

"@metamask/controllers@^8.0.0":
version "8.0.0"
resolved "https://registry.yarnpkg.com/@metamask/controllers/-/controllers-8.0.0.tgz#42ac5aaef67a03d3fe599a67a36597e01902ca8d"
integrity sha512-TrteMifsCxV1g3WHcSD1X98fF4hKep3sXZNGfrvkPqa8mrF03hJke21WBSTRtvJ3vkNLRWgi+5I6lVXFTzbYuQ==
"@metamask/controllers@^13.0.0":
version "13.0.0"
resolved "https://registry.yarnpkg.com/@metamask/controllers/-/controllers-13.0.0.tgz#f5bc12b89b5e67ad41d610213bda787be1e9c06c"
integrity sha512-6HDwyD+A37u2vCTje0Z6sifxzclsq2mOqI3YX133qSN+6rk/oCtGEOcJXjau3vNKog+gRzAR2do6/sU2y/01zw==
dependencies:
"@metamask/contract-metadata" "^1.24.0"
"@ethereumjs/common" "^2.3.1"
"@ethereumjs/tx" "^3.2.1"
"@metamask/contract-metadata" "^1.27.0"
"@types/uuid" "^8.3.0"
async-mutex "^0.2.6"
babel-runtime "^6.26.0"
eth-ens-namehash "^2.0.8"
eth-json-rpc-infura "^5.1.0"
eth-keyring-controller "^6.1.0"
eth-keyring-controller "^6.2.1"
eth-method-registry "1.1.0"
eth-phishing-detect "^1.1.13"
eth-phishing-detect "^1.1.14"
eth-query "^2.1.2"
eth-rpc-errors "^4.0.0"
eth-sig-util "^3.0.0"
ethereumjs-tx "^1.3.7"
ethereumjs-util "^6.1.0"
ethereumjs-util "^7.0.10"
ethereumjs-wallet "^1.0.1"
ethjs-unit "^0.1.6"
ethjs-util "^0.1.6"
human-standard-collectible-abi "^1.0.2"
human-standard-token-abi "^2.0.0"
immer "^8.0.1"
isomorphic-fetch "^3.0.0"
jsonschema "^1.2.4"
nanoid "^3.1.12"
punycode "^2.1.1"
single-call-balance-checker-abi "^1.0.0"
uuid "^8.3.2"
web3 "^0.20.7"
Expand All @@ -1526,12 +1524,12 @@
resolved "https://registry.yarnpkg.com/@metamask/safe-event-emitter/-/safe-event-emitter-2.0.0.tgz#af577b477c683fad17c619a78208cede06f9605c"
integrity sha512-/kSXhY692qiV1MXu6EeOZvg5nECLclxNXcKCxJ3cXQgYuRymRHpdx/t7JXfsK+JLjwA1e1c1/SBrlQYpusC29Q==

"@metamask/swaps-controller@^4.0.0":
version "4.0.0"
resolved "https://registry.yarnpkg.com/@metamask/swaps-controller/-/swaps-controller-4.0.0.tgz#60c1c1b8fd7ed90bb86a7402dccfee69322d29a6"
integrity sha512-D5D4Ld6rJRkJurAVUkWNTuijrQR4IqXaXh5mJAJn2IDgncXWK8XvIuIpFz/z6dURuoj/JIbfqMB2jX4GsWrBMA==
"@metamask/swaps-controller@^4.1.0":
version "4.1.0"
resolved "https://registry.yarnpkg.com/@metamask/swaps-controller/-/swaps-controller-4.1.0.tgz#c956e59bab0b9b4ae70ef1947bbc3407719d6ca6"
integrity sha512-HIa++6DJRhhBvXn9SeyScKhnhe3jfL2Pk3ztPJx+SxSClLispokrjP+0tec5UP3fB2BXYPZQKMSH1bF3tNVP2w==
dependencies:
"@metamask/controllers" "^8.0.0"
"@metamask/controllers" "^13.0.0"
abort-controller "^3.0.0"
async-mutex "^0.3.1"
bignumber.js "^9.0.1"
Expand Down

0 comments on commit d5d62ab

Please sign in to comment.