Skip to content

Commit

Permalink
Swaps: BSC Support (#2468)
Browse files Browse the repository at this point in the history
  • Loading branch information
wachunei authored Apr 23, 2021
1 parent b5ad243 commit c7b93e5
Show file tree
Hide file tree
Showing 34 changed files with 486 additions and 215 deletions.
27 changes: 19 additions & 8 deletions app/components/Nav/Main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import {
decodeApproveData
} from '../../../util/transactions';
import { BN } from 'ethereumjs-util';
import { safeToChecksumAddress } from '../../../util/address';
import Logger from '../../../util/Logger';
import contractMap from '@metamask/contract-metadata';
import MessageSign from '../../UI/MessageSign';
Expand All @@ -58,7 +57,7 @@ import AccountApproval from '../../UI/AccountApproval';
import ProtectYourWalletModal from '../../UI/ProtectYourWalletModal';
import MainNavigator from './MainNavigator';
import SkipAccountSecurityModal from '../../UI/SkipAccountSecurityModal';
import { swapsUtils, util } from '@estebanmino/controllers';
import { swapsUtils, util } from '@metamask/swaps-controller';
import SwapsLiveness from '../../UI/Swaps/SwapsLiveness';
import Analytics from '../../../core/Analytics';
import { ANALYTICS_EVENT_OPTS } from '../../../util/analytics';
Expand Down Expand Up @@ -310,16 +309,17 @@ const Main = props => {
async transactionMeta => {
if (transactionMeta.origin === TransactionTypes.MMM) return;

const to = safeToChecksumAddress(transactionMeta.transaction.to);
const to = transactionMeta.transaction.to?.toLowerCase();
const { data } = transactionMeta.transaction;

// if approval data includes metaswap contract
// if destination address is metaswap contract
if (
to === safeToChecksumAddress(swapsUtils.SWAPS_CONTRACT_ADDRESS) ||
to === swapsUtils.getSwapsContractAddress(props.chainId) ||
(data &&
data.substr(0, 10) === APPROVE_FUNCTION_SIGNATURE &&
decodeApproveData(data).spenderAddress === swapsUtils.SWAPS_CONTRACT_ADDRESS)
decodeApproveData(data).spenderAddress?.toLowerCase() ===
swapsUtils.getSwapsContractAddress(props.chainId))
) {
if (transactionMeta.origin === process.env.MM_FOX_CODE) {
autoSign(transactionMeta);
Expand Down Expand Up @@ -388,6 +388,7 @@ const Main = props => {
},
[
props.tokens,
props.chainId,
setEtherTransaction,
setTransactionObject,
toggleApproveModal,
Expand Down Expand Up @@ -568,6 +569,14 @@ const Main = props => {
}
});

// unapprovedTransaction effect
useEffect(() => {
Engine.context.TransactionController.hub.on('unapprovedTransaction', onUnapprovedTransaction);
return () => {
Engine.context.TransactionController.hub.removeListener('unapprovedTransaction', onUnapprovedTransaction);
};
}, [onUnapprovedTransaction]);

useEffect(() => {
initializeWalletConnect();
AppState.addEventListener('change', handleAppStateChange);
Expand Down Expand Up @@ -596,8 +605,6 @@ const Main = props => {
}
});

Engine.context.TransactionController.hub.on('unapprovedTransaction', onUnapprovedTransaction);

Engine.context.MessageManager.hub.on('unapprovedMessage', messageParams =>
onUnapprovedMessage(messageParams, 'eth')
);
Expand Down Expand Up @@ -628,7 +635,6 @@ const Main = props => {
lockManager.current.stopListening();
Engine.context.PersonalMessageManager.hub.removeAllListeners();
Engine.context.TypedMessageManager.hub.removeAllListeners();
Engine.context.TransactionController.hub.removeListener('unapprovedTransaction', onUnapprovedTransaction);
WalletConnect.hub.removeAllListeners();
removeConnectionStatusListener.current && removeConnectionStatusListener.current();
};
Expand Down Expand Up @@ -737,6 +743,10 @@ Main.propTypes = {
* Selected address
*/
selectedAddress: PropTypes.string,
/**
* Chain id
*/
chainId: PropTypes.string,
/**
* Network provider type
*/
Expand All @@ -755,6 +765,7 @@ const mapStateToProps = state => ({
lockTime: state.settings.lockTime,
thirdPartyApiMode: state.privacy.thirdPartyApiMode,
selectedAddress: state.engine.backgroundState.PreferencesController.selectedAddress,
chainId: state.engine.backgroundState.NetworkController.provider.chainId,
tokens: state.engine.backgroundState.AssetsController.tokens,
isPaymentRequest: state.transaction.paymentRequest,
dappTransactionModalVisible: state.modals.dappTransactionModalVisible,
Expand Down
9 changes: 5 additions & 4 deletions app/components/UI/AccountOverview/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { ScrollView, TextInput, StyleSheet, Text, View, TouchableOpacity, InteractionManager } from 'react-native';
import Clipboard from '@react-native-community/clipboard';
import { swapsUtils } from '@estebanmino/controllers';
import { swapsUtils } from '@metamask/swaps-controller';
import { connect } from 'react-redux';
import Engine from '../../../core/Engine';
import Analytics from '../../../core/Analytics';
Expand All @@ -21,6 +21,7 @@ import { renderFiat } from '../../../util/number';
import { renderAccountName } from '../../../util/address';
import { isMainNet } from '../../../util/networks';
import { getEther } from '../../../util/transactions';
import { isSwapsAllowed } from '../Swaps/utils';

import Identicon from '../Identicon';
import AssetActionButton from '../AssetActionButton';
Expand Down Expand Up @@ -257,7 +258,7 @@ class AccountOverview extends PureComponent {

goToSwaps = () =>
this.props.navigation.navigate('Swaps', {
sourceToken: swapsUtils.ETH_SWAPS_TOKEN_ADDRESS
sourceToken: swapsUtils.NATIVE_SWAPS_TOKEN_ADDRESS
});

render() {
Expand Down Expand Up @@ -331,7 +332,7 @@ class AccountOverview extends PureComponent {
</TouchableOpacity>
)}
</View>
<Text style={styles.amountFiat}>{fiatBalance}</Text>
{isMainNet(chainId) && <Text style={styles.amountFiat}>{fiatBalance}</Text>}
<TouchableOpacity style={styles.addressWrapper} onPress={this.copyAccountToClipboard}>
<EthereumAddress address={address} style={styles.address} type={'short'} />
</TouchableOpacity>
Expand All @@ -358,7 +359,7 @@ class AccountOverview extends PureComponent {
{AppConstants.SWAPS.ACTIVE && (
<AssetSwapButton
isFeatureLive={swapsIsLive}
isNetworkAllowed={AppConstants.SWAPS.ONLY_MAINNET ? isMainNet(chainId) : true}
isNetworkAllowed={isSwapsAllowed(chainId)}
onPress={this.goToSwaps}
isAssetAllowed
/>
Expand Down
19 changes: 12 additions & 7 deletions app/components/UI/AssetOverview/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { PureComponent } from 'react';
import { InteractionManager, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
import { swapsUtils } from '@estebanmino/controllers';
import { swapsUtils } from '@metamask/swaps-controller';
import AssetIcon from '../AssetIcon';
import Identicon from '../Identicon';
import AssetActionButton from '../AssetActionButton';
Expand All @@ -12,9 +12,10 @@ import { toggleReceiveModal } from '../../../actions/modals';
import { connect } from 'react-redux';
import { renderFromTokenMinimalUnit, balanceToFiat, renderFromWei, weiToFiat, hexToBN } from '../../../util/number';
import { safeToChecksumAddress } from '../../../util/address';
import { isMainNet } from '../../../util/networks';
import { getEther } from '../../../util/transactions';
import { newAssetTransaction } from '../../../actions/transaction';
import { isMainNet } from '../../../util/networks';
import { isSwapsAllowed } from '../Swaps/utils';
import { swapsLivenessSelector, swapsTokensObjectSelector } from '../../../reducers/swaps';
import Engine from '../../../core/Engine';
import Logger from '../../../util/Logger';
Expand Down Expand Up @@ -178,7 +179,7 @@ class AssetOverview extends PureComponent {

goToSwaps = () => {
this.props.navigation.navigate('Swaps', {
sourceToken: this.props.asset.isETH ? swapsUtils.ETH_SWAPS_TOKEN_ADDRESS : this.props.asset.address
sourceToken: this.props.asset.isETH ? swapsUtils.NATIVE_SWAPS_TOKEN_ADDRESS : this.props.asset.address
});
};

Expand Down Expand Up @@ -249,12 +250,16 @@ class AssetOverview extends PureComponent {
let balance, balanceFiat;
if (isETH) {
balance = renderFromWei(accounts[selectedAddress] && accounts[selectedAddress].balance);
balanceFiat = weiToFiat(hexToBN(accounts[selectedAddress].balance), conversionRate, currentCurrency);
balanceFiat = isMainNet(chainId)
? weiToFiat(hexToBN(accounts[selectedAddress].balance), conversionRate, currentCurrency)
: null;
} else {
const exchangeRate = itemAddress in tokenExchangeRates ? tokenExchangeRates[itemAddress] : undefined;
balance =
itemAddress in tokenBalances ? renderFromTokenMinimalUnit(tokenBalances[itemAddress], decimals) : 0;
balanceFiat = balanceToFiat(balance, conversionRate, exchangeRate, currentCurrency);
balanceFiat = isMainNet(chainId)
? balanceToFiat(balance, conversionRate, exchangeRate, currentCurrency)
: null;
}
// choose balances depending on 'primaryCurrency'
if (primaryCurrency === 'ETH') {
Expand All @@ -275,7 +280,7 @@ class AssetOverview extends PureComponent {
<Text style={styles.amount} testID={'token-amount'}>
{mainBalance}
</Text>
<Text style={styles.amountFiat}>{secondaryBalance}</Text>
{secondaryBalance && <Text style={styles.amountFiat}>{secondaryBalance}</Text>}
</>
)}
</View>
Expand Down Expand Up @@ -303,7 +308,7 @@ class AssetOverview extends PureComponent {
{AppConstants.SWAPS.ACTIVE && (
<AssetSwapButton
isFeatureLive={swapsIsLive}
isNetworkAllowed={AppConstants.SWAPS.ONLY_MAINNET ? isMainNet(chainId) : true}
isNetworkAllowed={isSwapsAllowed(chainId)}
isAssetAllowed={isETH || address?.toLowerCase() in swapsTokens}
onPress={this.goToSwaps}
/>
Expand Down
9 changes: 9 additions & 0 deletions app/components/UI/CustomGas/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,10 @@ class CustomGas extends PureComponent {
* Object BN containing gas price
*/
gasPrice: PropTypes.object,
/**
* Object BN containing mininum gas price
*/
minimumGasPrice: PropTypes.object,
/**
* Callback to modify parent state
*/
Expand Down Expand Up @@ -488,6 +492,11 @@ class CustomGas extends PureComponent {
const warningSufficientFunds = this.hasSufficientFunds(customGasLimitBN, gasPriceBNWei);
let warningGasPrice;
let warningGasPriceHigh = '';
if (this.onlyAdvanced() && this.props.minimumGasPrice) {
if (parseInt(gasPrice) < parseInt(fromWei(this.props.minimumGasPrice, 'gwei'))) {
warningGasPrice = strings('transaction.low_gas_price');
}
}
if (this.props.basicGasEstimates) {
if (parseInt(gasPrice) < parseInt(this.props.basicGasEstimates.safeLowGwei))
warningGasPrice = strings('transaction.low_gas_price');
Expand Down
10 changes: 8 additions & 2 deletions app/components/UI/DrawerView/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Icon from 'react-native-vector-icons/FontAwesome';
import FeatherIcon from 'react-native-vector-icons/Feather';
import MaterialIcon from 'react-native-vector-icons/MaterialCommunityIcons';
import { colors, fontStyles } from '../../../styles/common';
import { hasBlockExplorer, findBlockExplorerForRpc, getBlockExplorerName } from '../../../util/networks';
import { hasBlockExplorer, findBlockExplorerForRpc, getBlockExplorerName, isMainNet } from '../../../util/networks';
import Identicon from '../Identicon';
import StyledButton from '../StyledButton';
import AccountList from '../AccountList';
Expand Down Expand Up @@ -338,6 +338,10 @@ class DrawerView extends PureComponent {
* Wizard onboarding state
*/
wizard: PropTypes.object,
/**
* Chain Id
*/
chainId: PropTypes.string,
/**
* Current provider ticker
*/
Expand Down Expand Up @@ -830,6 +834,7 @@ class DrawerView extends PureComponent {
selectedAddress,
keyrings,
currentCurrency,
chainId,
ticker,
seedphraseBackedUp
} = this.props;
Expand Down Expand Up @@ -876,7 +881,7 @@ class DrawerView extends PureComponent {
</Text>
<Icon name="caret-down" size={24} style={styles.caretDown} />
</View>
<Text style={styles.accountBalance}>{fiatBalanceStr}</Text>
{isMainNet(chainId) && <Text style={styles.accountBalance}>{fiatBalanceStr}</Text>}
<EthereumAddress
address={account.address}
style={styles.accountAddress}
Expand Down Expand Up @@ -1065,6 +1070,7 @@ const mapStateToProps = state => ({
receiveModalVisible: state.modals.receiveModalVisible,
passwordSet: state.user.passwordSet,
wizard: state.wizard,
chainId: state.engine.backgroundState.NetworkController.provider.chainId,
ticker: state.engine.backgroundState.NetworkController.provider.ticker,
tokens: state.engine.backgroundState.AssetsController.tokens,
tokenBalances: state.engine.backgroundState.TokenBalancesController.contractBalances,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ function TransactionNotification(props) {
const {
selectedAddress,
ticker,
chainId,
conversionRate,
currentCurrency,
exchangeRate,
Expand All @@ -194,6 +195,7 @@ function TransactionNotification(props) {
tx,
selectedAddress,
ticker,
chainId,
conversionRate,
currentCurrency,
exchangeRate,
Expand Down Expand Up @@ -338,6 +340,10 @@ TransactionNotification.propTypes = {
* Current provider ticker
*/
ticker: PropTypes.string,
/**
* Current provider chainId
*/
chainId: PropTypes.string,
/**
* ETH to current currency conversion rate
*/
Expand Down Expand Up @@ -374,6 +380,7 @@ const mapStateToProps = state => ({
selectedAddress: state.engine.backgroundState.PreferencesController.selectedAddress,
transactions: state.engine.backgroundState.TransactionController.transactions,
ticker: state.engine.backgroundState.NetworkController.provider.ticker,
chainId: state.engine.backgroundState.NetworkController.provider.chainId,
tokens: state.engine.backgroundState.AssetsController.tokens.reduce((tokens, token) => {
tokens[token.address] = token;
return tokens;
Expand Down
Loading

0 comments on commit c7b93e5

Please sign in to comment.