Skip to content

Commit

Permalink
Add 'Connect Wallet' button + user details modal
Browse files Browse the repository at this point in the history
  • Loading branch information
tomarsachin2271 committed Jul 21, 2021
1 parent 595dddb commit fe47a34
Show file tree
Hide file tree
Showing 22 changed files with 5,715 additions and 462 deletions.
5,042 changes: 4,898 additions & 144 deletions package-lock.json

Large diffs are not rendered by default.

9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@
"@testing-library/user-event": "^7.1.2",
"awesome-debounce-promise": "^2.1.0",
"bnc-notify": "^1.6.1",
"bnc-onboard": "^1.30.0",
"clsx": "^1.1.1",
"eth-icon": "^1.0.1",
"eth-sig-util": "^2.5.2",
"ethereumjs-abi": "^0.6.8",
"ethereumjs-tx": "^2.1.2",
"ethereumjs-util": "^7.0.7",
"ethers": "^5.0.24",
"ms": "^2.1.3",
"react": "^16.12.0",
"react-copy-to-clipboard": "^5.0.3",
"react-dom": "^16.12.0",
"react-notifications-component": "^3.1.0",
"react-redux": "^7.2.2",
Expand All @@ -34,9 +37,9 @@
"web3": "^1.2.5-rc.0"
},
"scripts": {
"start": "PORT=6005 react-scripts start",
"start:prod": "REACT_APP_ENV=prod PORT=6005 react-scripts start",
"start:test": "REACT_APP_ENV=test PORT=6005 react-scripts start",
"start": "PORT=6005 REACT_APP_ENV=test REACT_APP_DAPP_ID=95690f7c-6c8a-474c-8931-06229df9fba8 react-scripts start",
"start:prod": "REACT_APP_ENV=prod REACT_APP_DAPP_ID=0f962064-606e-434e-9512-785b1b7fa285 PORT=6005 react-scripts start",
"start:test": "REACT_APP_ENV=test REACT_APP_DAPP_ID=0f962064-606e-434e-9512-785b1b7fa285 PORT=6005 react-scripts start",
"build": "react-scripts build",
"build:prod": "REACT_APP_ENV=prod react-scripts build",
"build:test": "REACT_APP_ENV=test react-scripts build",
Expand Down
236 changes: 151 additions & 85 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import ArrowIcon from './assets/arrow.svg';
import ReactNotification from 'react-notifications-component';
import 'react-notifications-component/dist/theme.css';
import { store } from 'react-notifications-component';
import Onboard from 'bnc-onboard'

import { BigNumber, ethers } from "ethers";
// import {EthUtil} from "ethereumjs-util";
Expand All @@ -53,7 +54,9 @@ import {
updateTransferStepsContentArray,
updateTransferStepsLabelArray,
updateEstimatedAmountToGet,
updateFromChainProvider, updateToChainProvider
updateFromChainProvider, updateToChainProvider,
updateSelectedWallet, updateNetworkState,
updateUserState
} from "./redux";
import Faucet from "./components/Faucet";
import Header from "./components/Header";
Expand Down Expand Up @@ -119,6 +122,7 @@ const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 150,
zIndex: "0!important"
},
estimationsContainer: {
background: "#555",
Expand Down Expand Up @@ -270,7 +274,7 @@ const useStyles = makeStyles((theme) => ({

const fromChainList = config.supportedChainArrray;
const toChainList = config.supportedChainArrray;
let notify;
let notify, onboard;

const getTokenGasPrice = (tokenAddress, networkId, fetchOptions) => fetch(`${config.hyphen.baseURL}${config.hyphen.getTokenGasPricePath}?tokenAddress=${tokenAddress}&networkId=${networkId}`, fetchOptions)
const getTokenGasPriceDebounced = AwesomeDebouncePromise(getTokenGasPrice, 500);
Expand Down Expand Up @@ -332,97 +336,102 @@ function App() {
const [amountInputDisabled, setAmountInputDisabled] = useState(true);
const [openTransferActivity, setOpenTransferActivity] = useState(false);

useEffect(() => {
async function init() {
if (
typeof window.ethereum !== "undefined" &&
window.ethereum.isMetaMask
) {
// Ethereum user detected. You can now use the provider.
const provider = window["ethereum"];
await provider.enable();
ethersProvider = new ethers.providers.Web3Provider(provider, "any");

let network = await ethersProvider.getNetwork();
setWalletChainId(network.chainId);

let walletChain = config.chainIdMap[network.chainId];

if(network && network.chainId && Object.keys(config.chainIdMap).includes(network.chainId.toString()))
onFromChainSelected({target: {value: network.chainId}});

initBlocknativeNotify(network);

let biconomyOptions = {
enable: false
};

if(walletChain) {
if(walletChain.biconomy && walletChain.biconomy.enable && walletChain.biconomy.apiKey) {
biconomyOptions.enable = true;
biconomyOptions.debug = true;
biconomyOptions.apiKey = walletChain.biconomy.apiKey
} else {
console.log(`Biconomy is not enabled for ${walletChain.name}`);
}
async function init(provider) {
if (provider) {
dispatch(updateTransferButtonState(false, "Give wallet approval"));
console.log("Enable wallet to give permission to use the address");
await provider.enable();
ethersProvider = new ethers.providers.Web3Provider(provider, "any");

console.log("Getting current network from wallet");
let network = await ethersProvider.getNetwork();
setWalletChainId(network.chainId);

let walletChain = config.chainIdMap[network.chainId];

if(network && network.chainId && Object.keys(config.chainIdMap).includes(network.chainId.toString()))
onFromChainSelected({target: {value: network.chainId}});

console.log("Initializing blocknative notify");
initBlocknativeNotify(network);

let biconomyOptions = {
enable: false
};

if(walletChain) {
if(walletChain.biconomy && walletChain.biconomy.enable && walletChain.biconomy.apiKey) {
biconomyOptions.enable = true;
biconomyOptions.debug = true;
biconomyOptions.apiKey = walletChain.biconomy.apiKey
} else {
console.log(`Biconomy is not enabled for ${walletChain.name}`);
}
}

let hyphen = new Hyphen(provider, {
debug: true,
environment: config.getEnv(),
infiniteApproval: true,
biconomy: biconomyOptions,
// onFundsTransfered: async (data) => {

dispatch(updateTransferButtonState(false, "Initializing Hyphen"));
let hyphen = new Hyphen(provider, {
debug: true,
environment: config.getEnv(),
infiniteApproval: true,
biconomy: biconomyOptions,
// onFundsTransfered: async (data) => {

// }
});

await hyphen.init();

signer = ethersProvider.getSigner();
let userAddress = await signer.getAddress();
if (userAddress) {
setUserAddress(userAddress);
}

signer = ethersProvider.getSigner();
let userAddress = await signer.getAddress();
if (userAddress) {
setUserAddress(userAddress);
}

console.log("Initializing Hyphen");
await hyphen.init();
console.log("Hyphen initialized");

// updateFaucetBalance();
setHyphen(hyphen);

ethersProvider.on("network", (newNetwork, oldNetwork) => {
// When a Provider makes its initial connection, it emits a "network"
// event with a null oldNetwork along with the newNetwork. So, if the
// oldNetwork exists, it represents a changing network
if (oldNetwork) {
window.location.reload();
}
});

// try {
// ethersProvider.on("block", (blockNumber) => {
// updateFaucetBalance();
// });
// } catch (error) {
// console.log(error);
// }

// Hanlde user address change
if(provider.on) {
provider.on('accountsChanged', function (accounts) {
console.log(`Address changed EVENT`);
console.log(`New account info`, accounts);

if(accounts && accounts.length > 0) {
let newUserAddress = accounts[0];
if (newUserAddress) {
setUserAddress(newUserAddress);
}
}
})
// updateFaucetBalance();
setHyphen(hyphen);

ethersProvider.on("network", (newNetwork, oldNetwork) => {
// When a Provider makes its initial connection, it emits a "network"
// event with a null oldNetwork along with the newNetwork. So, if the
// oldNetwork exists, it represents a changing network
if (oldNetwork) {
window.location.reload();
}
} else {
showErrorMessage("Metamask not installed");
});

dispatch(updateTransferButtonState(false, "Enter an amount"));
// try {
// ethersProvider.on("block", (blockNumber) => {
// updateFaucetBalance();
// });
// } catch (error) {
// console.log(error);
// }

// Hanlde user address change
if(provider.on) {
provider.on('accountsChanged', function (accounts) {
console.log(`Address changed EVENT`);
console.log(`New account info`, accounts);

if(accounts && accounts.length > 0) {
let newUserAddress = accounts[0];
if (newUserAddress) {
setUserAddress(newUserAddress);
}
}
})
}
} else {
console.log("provider is not defined");
}
}

useEffect(() => {
try {
init();
} catch(error) {
Expand Down Expand Up @@ -453,13 +462,56 @@ function App() {
}
}

const updateWallet = (walletName) => {
if(walletName) {
dispatch(updateSelectedWallet(walletName));
console.log(walletName);
localStorage.setItem(config.selectedWalletKey, walletName);
}
}

const connectToLastSelectedWallet = () => {
if(localStorage) {
let lastSelectedWallet = localStorage.getItem(config.selectedWalletKey);
if(lastSelectedWallet) {
switch(lastSelectedWallet) {
case config.WALLET.METAMASK:
if (window && typeof window.ethereum !== "undefined" &&
window.ethereum.isMetaMask) {
let _provider = window["ethereum"];
init(_provider);
updateWallet(lastSelectedWallet);
}
break;
}
}
}
}

useEffect(() => {
checkForNegativeAmount(estimatedTokensToGet);
}, [estimatedTokensToGet])


useEffect(() => {
if(selectedFromChain) {

let initOnboard = async () => {
// Initialize Onboard
onboard = Onboard({
...selectedFromChain.onboardConfig,
hideBranding: true,
subscriptions: {
wallet: wallet => {
init(wallet.provider);
updateWallet(wallet.name);
}
}
});
}

initOnboard();
connectToLastSelectedWallet();
let rpcUrl = selectedFromChain.rpcUrl;
if(rpcUrl) {
let provider = new ethers.providers.JsonRpcProvider(rpcUrl);
Expand All @@ -481,6 +533,10 @@ function App() {
useEffect(() => {
console.log("Selected token changed", selectedToken)
selectedTokenRef.current = selectedToken;
if(userAddress) {
dispatch(updateUserState({userAddress: userAddress.toLowerCase()}));
}

if (selectedToken !== undefined && selectedToken.address && signer && ethersProvider && userAddress) {
dispatch(updateSelectedTokenBalance(undefined, undefined));
dispatch(updateMinDeposit(undefined));
Expand All @@ -496,6 +552,15 @@ function App() {
calculateTransactionFee(selectedTokenAmount);
}, [selectedTokenBalance])

const onClickConnectWallet = async () => {
if(onboard) {
let isWalletSelected = await onboard.walletSelect();
if(isWalletSelected) {
await onboard.walletCheck();
}
}
}

const updateUserBalance = async (userAddress, selectedToken) => {
let status = await checkNetwork();
if (status) {
Expand Down Expand Up @@ -1276,7 +1341,8 @@ function App() {
/>

<Header switchButtonText={switchNetworkText} showSwitchNetworkButton={showSwitchNetworkButton}
onClickNetworkChange={onClickSwitchNetwork} selectedFromChain={selectedFromChain}/>
onClickNetworkChange={onClickSwitchNetwork} selectedFromChain={selectedFromChain}
connectWalletText={config.connectWalletText} connectWallet={onClickConnectWallet}/>

<div className="App">
{ (selectedFromChain.name === "Mumbai" || selectedFromChain.name === "Goerli") &&
Expand Down
3 changes: 3 additions & 0 deletions src/assets/copy-icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/assets/cross-icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit fe47a34

Please sign in to comment.