Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update project configuration and fix bug in ConnectWallet component #9

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"editor.formatOnSave": true
"editor.formatOnSave": true,
"i18n-ally.localesPaths": [
"i18n",
"locale"
]
}
Binary file added .yarn/install-state.gz
Binary file not shown.
893 changes: 893 additions & 0 deletions .yarn/releases/yarn-4.0.2.cjs

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-4.0.2.cjs
4 changes: 2 additions & 2 deletions common/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export function scrollToSection(id, offset = 0) {

export function getEtherScanDomain() {
return process.env.NEXT_PUBLIC_CHAIN_ID === '1'
? 'etherscan.io'
: 'rinkeby.etherscan.io';
? 'optimistic.etherscan.io'
: 'goerli-optimism.etherscan.io';
}

export function getOpenSeaDomain() {
Expand Down
164 changes: 22 additions & 142 deletions components/ConnectWallet.js
Original file line number Diff line number Diff line change
@@ -1,149 +1,48 @@
import React, { useState, useContext, useEffect } from 'react';
'use client';
import React, { useState, useEffect } from 'react';
import { Chip, Box, Typography, Button } from '@mui/material';
import { ethers } from 'ethers';
import Web3Modal from 'web3modal';
import WalletConnectProvider from '@walletconnect/web3-provider';

import { useConnectModal, useChainModal } from '@rainbow-me/rainbowkit';
import { SimpleModal } from './showMessage';
import contractABI from '../abi.json';
import showMessage from './showMessage';
import { formatAddress } from '../common/utils';
import { WalletContext } from '../hooks/useWallet';

const CHAIN_ID = process.env.NEXT_PUBLIC_CHAIN_ID;
const NETWORK = CHAIN_ID === '1' ? 'mainnet' : 'rinkeby';

const providerOptions = {
walletconnect: {
package: WalletConnectProvider,
options: {
infuraId: process.env.NEXT_PUBLIC_INFURA_PROJECT_ID,
},
},
};

let web3ModelInstance;
if (typeof window !== 'undefined') {
web3ModelInstance = new Web3Modal({
network: NETWORK,
cacheProvider: true,
providerOptions,
});
}
import { useAccount, useNetwork } from 'wagmi';

let provider;
let signer;
let instance;
let contract;

export async function connectWallet() {
if (!instance) {
instance = await web3ModelInstance.connect();
// https://docs.ethers.io/v5/api/providers/
provider = new ethers.providers.Web3Provider(instance);
// https://docs.ethers.io/v5/api/signer/
signer = provider.getSigner();
contract = new ethers.Contract(
process.env.NEXT_PUBLIC_CONTRACT_ADDRESS,
contractABI,
provider
);
}

return { provider, signer, web3Instance: instance, contract };
}

async function disconnectWallet() {
provider = undefined;
signer = undefined;
instance = undefined;
contract = undefined;
await web3ModelInstance.clearCachedProvider();
}
const CHAIN_ID = process.env.NEXT_PUBLIC_CHAIN_ID ?? '10';
const NETWORK = CHAIN_ID === '10' ? 'Optimism Mainnet' : 'Optimism Testnet';

export default function ConnectWallet(props) {
const [loading, setLoading] = useState(false);
const { address, fullAddress, setAddress, setFullAddress } =
useContext(WalletContext);

const { address, isConnected } = useAccount();
const [visible, setVisible] = useState(false);
const { openConnectModal } = useConnectModal();
const { openChainModal } = useChainModal();
const { chain } = useNetwork();

// try to connect after the page loaded
useEffect(() => {
(async () => {
if (!fullAddress && web3ModelInstance?.cachedProvider) {
try {
const { provider, signer } = await connectWallet();
const { chainId } = await provider.getNetwork();
if (chainId !== parseInt(CHAIN_ID)) {
return;
}
const address = await signer.getAddress();
const ens = await provider.lookupAddress(address);
setAddress(ens || formatAddress(address));
setFullAddress(address);
} catch (err) {
await disconnectWallet();
setAddress(null);
setFullAddress(null);
}
}
})();
}, []);

if (address && !loading) {
return (
<Chip
label={address}
color="primary"
onDelete={async () => {
await disconnectWallet();
setAddress(null);
}}
/>
);
}
if (chain?.id != CHAIN_ID && isConnected) {
setVisible(true);
} else {
setVisible(false);
}
}, [chain]);

return (
<>
<Chip
style={{ fontSize: 16 }}
label={loading ? 'Connecting...' : 'Connect Wallet'}
label={loading ? 'Connecting...' : address ? address : 'Connect Wallet'}
color="primary"
onClick={async () => {
setLoading(true);
try {
const { provider, signer, web3Instance } = await connectWallet();
const { chainId } = await provider.getNetwork();
if (chainId !== parseInt(CHAIN_ID)) {
setVisible(true);
return;
}
const address = await signer.getAddress();
const ens = await provider.lookupAddress(address);
setAddress(ens || formatAddress(address));
setFullAddress(address);
web3Instance.on('accountsChanged', async (accounts) => {
if (accounts.length === 0) {
await disconnectWallet();
setAddress(null);
setFullAddress(null);
} else {
const address = accounts[0];
const ens = await provider.lookupAddress(address);
setAddress(ens || formatAddress(address));
setFullAddress(address);
}
});
openConnectModal && openConnectModal();
} catch (err) {
await disconnectWallet();
setAddress(null);
setFullAddress(null);
showMessage({
type: 'error',
title: 'Failed to connect wallet',
body: err.message,
});
} finally {
setLoading(false);
}
}}
/>
Expand All @@ -167,29 +66,10 @@ export default function ConnectWallet(props) {
<Button
variant="contained"
onClick={async () => {
try {
await window?.ethereum?.request({
method: 'wallet_switchEthereumChain',
params: [
{
chainId: `0x${CHAIN_ID}`,
},
],
});
window.location.reload();
} catch (err) {
if (err.code === 4902 && CHAIN_ID === '4') {
alert('Please enable Rinkeby network first.');
}
showMessage({
type: 'error',
title: 'Failed to switch network',
body: err.message,
});
}
openChainModal();
}}
>
Change Network to {NETWORK}
Change Network
</Button>
</Box>
</Box>
Expand Down
56 changes: 33 additions & 23 deletions components/Donation.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
'use client';
import React, { useState, useContext } from 'react';
import { Button, Link, Box, Typography, Input } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { ethers } from 'ethers';
import { t } from '@lingui/macro';

import ConnectWallet, { connectWallet } from './ConnectWallet';
import { WalletContext } from '../hooks/useWallet';
import ConnectWallet from './ConnectWallet';
import { useSendTransaction, usePrepareSendTransaction } from 'wagmi';
import showMessage, { SimpleModal } from './showMessage';
import { getEtherScanDomain } from '../common/utils';

import { useAccount, useNetwork } from 'wagmi';
import { parseEther } from 'viem';
function NumberComponent(props) {
return (
<Input
Expand All @@ -29,8 +29,32 @@ function NumberComponent(props) {
export function DonationModal(props) {
const [amount, setAmount] = useState(0.1);
const [tx, setTx] = useState(null);
const { fullAddress } = useContext(WalletContext);

const { address } = useAccount();
const { sendTransaction } = useSendTransaction({
to: '0x1b8556BDc549D20De33eCba674CF3Bbb88CfEd0A',
value: parseEther(amount.toString()),
onSuccess: (tx) => {
showMessage({
title: `Success to donate!`,
type: 'success',
});
setTx(tx);
},
onError: (error) => {
showMessage({
type: 'error',
title: 'Failed to donate',
body: () => {
if (error.toString().includes('rejected')) {
return 'User Rejected Request';
} else {
return 'Error';
}
},
});
console.error(error);
},
});
return (
<SimpleModal
title={t`section-donation-title`}
Expand Down Expand Up @@ -73,26 +97,12 @@ export function DonationModal(props) {
/>{' '}
ETH
</Box>
{fullAddress ? (
{address ? (
<Button
variant="outlined"
size="small"
onClick={async () => {
try {
const { signer } = await connectWallet();
let txValue = {
to: '0x1b8556BDc549D20De33eCba674CF3Bbb88CfEd0A',
value: ethers.utils.parseEther(amount.toString()),
};
const tx = await signer.sendTransaction(txValue);
setTx(tx);
} catch (err) {
showMessage({
type: 'error',
title: 'Failed to donate',
body: err.message,
});
}
sendTransaction?.();
}}
>
{t`section-donate-content-6`}
Expand Down
Loading