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

Feat/web3 v8 #463

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
136 changes: 90 additions & 46 deletions containers/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,40 @@ import { createContainer } from "unstated-next";
import { ethers } from "ethers";
import { Observable } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { useWeb3React } from "@web3-react/core";
import { useWeb3React, Web3ReactHooks, getPriorityConnector } from "@web3-react/core";
import { Provider as MulticallProvider, setMulticallAddress } from "ethers-multicall";
import { useRouter } from "next/router";
import { ChainNetwork, Chains, RawChain } from "picklefinance-core/lib/chain/Chains";
import { PickleCore } from "./Jars/usePickleCore";
import { AddEthereumChainParameter, Connector } from "@web3-react/types";
import { getHooks } from "features/Connection/Web3Modal/Connectors";
import { MetaMask } from "@web3-react/metamask";
import { WalletConnect } from "@web3-react/walletconnect";
import { CoinbaseWallet } from "@web3-react/coinbase-wallet";

type Network = ethers.providers.Network;

// See https://eips.ethereum.org/EIPS/eip-3085 and
// https://docs.metamask.io/guide/rpc-api.html#wallet-addethereumchain
interface AddEthereumChainParameter {
chainId: string;
blockExplorerUrls?: string[];
chainName?: string;
iconUrls?: string[];
nativeCurrency?: {
name: string;
symbol: string;
decimals: number;
};
rpcUrls?: string[];
}
// interface AddEthereumChainParameter {
// chainId: string;
// blockExplorerUrls?: string[];
// chainName?: string;
// iconUrls?: string[];
// nativeCurrency?: {
// name: string;
// symbol: string;
// decimals: number;
// };
// rpcUrls?: string[];
// }

export const chainToChainParams = (
chain: RawChain | undefined,
): AddEthereumChainParameter | undefined => {
if (!chain) return undefined;
return {
chainId: "0x" + chain.chainId.toString(16),
chainId: chain.chainId,
chainName: chain.networkVisible,
nativeCurrency: {
name: chain.gasTokenSymbol.toUpperCase(),
Expand All @@ -44,7 +49,13 @@ export const chainToChainParams = (
};

function useConnection() {
const { account, library, chainId } = useWeb3React();
const {
account,
/* library, */ chainId,
/* provider, */ connector,
isActive,
ENSName,
} = useWeb3React();
const router = useRouter();
const { pickleCore } = PickleCore.useContainer();

Expand All @@ -53,66 +64,96 @@ function useConnection() {

const [multicallProvider, setMulticallProvider] = useState<MulticallProvider | null>(null);

const [hooks, setHooks] = useState<Web3ReactHooks>();
const [provider, setProvider] = useState<ReturnType<Web3ReactHooks["useProvider"]>>();
const [signer, setSigner] = useState<ethers.providers.JsonRpcSigner>();

const [network, setNetwork] = useState<Network | null>(null);
const [blockNum, setBlockNum] = useState<number | null>(null);

const switchChain = async (chainId: number) => {
const switchChain = async (desiredChainId: number) => {
// if pfcore is not loaded yet, return
if (!pickleCore) return false;
let method: string;
let params: any[];
if (chainId === 1) {
method = "wallet_switchEthereumChain";
params = [{ chainId: "0x1" }];
} else {
method = "wallet_addEthereumChain";
method = "wallet_addEthereumChain";
const param = chainToChainParams(pickleCore.chains.find((x) => x.chainId === chainId));
if (param === undefined || param === null) return false;
params = [param];
}
// if we're already connected to the desired chain, return
if (desiredChainId === chainId) return true;
// if they want to connect to the default chain and we're already connected, return
if (desiredChainId === -1 && chainId !== undefined) return true;

try {
await library.provider.request({
method: method,
params: params,
});
if (connector instanceof WalletConnect /* || connector instanceof Network */) {
await connector.activate(desiredChainId === -1 ? undefined : desiredChainId);
} else {
await connector.activate(
desiredChainId === -1 ? undefined : chainToChainParams(rawChainFor(desiredChainId)),
);
}
return true;
} catch (e) {
return false;
console.log("switchChainError");
console.log(e);
}
return false;
};

const rawChainFor = (network: ChainNetwork): RawChain | undefined => {
// const rawChainFor = (network: ChainNetwork): RawChain | undefined => {
// return pickleCore === undefined || pickleCore === null
// ? undefined
// : pickleCore.chains.find((z) => z.network === network);
// };
const rawChainFor = (network: ChainNetwork | number): RawChain | undefined => {
return pickleCore === undefined || pickleCore === null
? undefined
: pickleCore.chains.find((z) => z.network === network);
: pickleCore.chains.find((z) => z.network === network || z.chainId === network);
};

const networks = Chains.list().filter((x) => rawChainFor(x) !== undefined);
const supportedChainParams = networks.map((x) => {
const rawChain = rawChainFor(x);
return chainToChainParams(rawChain);
});
const supportedChains = supportedChainParams;

// get the currently connected connector hooks & provider
const currentHooks = getHooks(connector);
// hooks provider gives back a signer, the useWeb3React provider does not!
const currentProvider = currentHooks?.useProvider();

// useEffect(() => {
// if (connector && tryHooks && tryProvider) {
// const signer = tryProvider.getSigner();

// setProvider(tryProvider);
// setSigner(signer);
// setHooks(hooks);
// }
// }, [account, chainId, connector]);

// create observable to stream new blocks
useEffect(() => {
if (library) {
library.getNetwork().then((network: any) => setNetwork(network));
// update provider, hooks and signer each time provider changes (upon chain, account or connector changes)
if (pickleCore && currentHooks && currentProvider && currentProvider !== provider) {
// set the network
currentProvider.getNetwork().then((network: any) => setNetwork(network));

// set multicall address
Chains.list().map((x) => {
const raw: RawChain | undefined = rawChainFor(x);
if (raw && raw.multicallAddress) {
setMulticallAddress(raw.chainId, raw.multicallAddress);
}
});

const _multicallProvider = new MulticallProvider(library);
_multicallProvider.init().then(() => setMulticallProvider(_multicallProvider));
// set multicallProvider
const _multicallProvider = new MulticallProvider(currentProvider, chainId);
setMulticallProvider(_multicallProvider);

// reload the page on chain changes
const { ethereum } = window as any;
ethereum?.on("chainChanged", () => router.reload());

// create an observable to track the latest chain blocks
const observable = new Observable<number>((subscriber) => {
library.on("block", (blockNumber: number) => subscriber.next(blockNumber));
currentProvider.on("block", (blockNumber: number) => subscriber.next(blockNumber));
});

// debounce to prevent subscribers making unnecessary calls
Expand All @@ -121,25 +162,28 @@ function useConnection() {
setBlockNum(blockNumber);
}
});
} else {
setMulticallProvider(null);
setBlockNum(null);

setProvider(currentProvider);
setHooks(currentHooks);
setSigner(currentProvider.getSigner());
}
}, [library, pickleCore]);
}, [pickleCore, connector, provider, chainId, account]);

const chainName = pickleCore?.chains.find((x) => x.chainId === chainId)?.network || null;

return {
multicallProvider,
provider: library,
provider,
address: account,
network,
blockNum,
signer: library?.getSigner(),
chainId,
chainName,
switchChain,
supportedChains,
connector,
hooks,
signer,
};
}

Expand Down
2 changes: 1 addition & 1 deletion features/Connection/DesktopNetworkIndicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export const DesktopNetworkIndicator: FC = () => {
const { ensName } = useENS(address);
const { pickleCore } = PickleCore.useContainer();

const shortAddress = `${address?.substr(0, 5)}…${address?.substr(-4)}`;
const shortAddress = `${address?.substring(0, 5)}…${address?.substring(38)}`;

const handleSwitchChain = async (newChainId: number) => {
if (chainId === newChainId) return;
Expand Down
37 changes: 30 additions & 7 deletions features/Connection/Web3Modal/ConnectorItem.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import styled, { css } from "styled-components";
import Loader from "react-loader-spinner";
import { FC, MouseEventHandler } from "react";
import { FC, MouseEventHandler, useEffect } from "react";
import { Web3ReactHooks } from "@web3-react/core";
import { Connector } from "@web3-react/types";

interface ConnectorItemProps {
icon: string;
title: string;
onClick: MouseEventHandler<HTMLDivElement>;
loading: boolean;
disabled: boolean;
onClick: Function; //MouseEventHandler<HTMLDivElement>;
ethereum: any;
connector: Connector;
hooks: Web3ReactHooks;
}

interface ContainerProps {
Expand Down Expand Up @@ -49,10 +52,30 @@ const LoaderContainer = styled.div`
transform: translate(-50%, -50%);
`;

const ConnectorItem: FC<ConnectorItemProps> = ({ icon, title, onClick, loading, disabled }) => {
const ConnectorItem: FC<ConnectorItemProps> = ({
icon,
title,
onClick,
ethereum,
connector,
hooks,
}) => {
const { useError, useIsActivating, useIsActive } = hooks;
const error = useError();
const isActivating = useIsActivating();
const isActive = useIsActive();

// attempt to connect eagerly on mount
useEffect(() => {
if (connector.connectEagerly) void connector.connectEagerly();
}, []);

return (
<StyledContainer onClick={onClick} disabled={loading || disabled}>
{loading && (
<StyledContainer
onClick={() => onClick(connector, error, isActivating, isActive)}
disabled={isActivating || !ethereum}
>
{isActivating && (
<LoaderContainer>
<Loader type="TailSpin" color="#aaa" height={50} width={50} />
</LoaderContainer>
Expand Down
93 changes: 68 additions & 25 deletions features/Connection/Web3Modal/Connectors.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { InjectedConnector } from "@web3-react/injected-connector";
import { WalletConnectConnector } from "@web3-react/walletconnect-connector";
import { WalletLinkConnector } from "@web3-react/walletlink-connector";
import { CloverConnector } from "@clover-network/clover-connector";
import { Chains } from "picklefinance-core";
const POLLING_INTERVAL = 12000;

import { initializeConnector, Web3ReactHooks } from '@web3-react/core'
import { MetaMask } from '@web3-react/metamask'
import type { Connector } from '@web3-react/types'
import { WalletConnect } from '@web3-react/walletconnect'
import { CoinbaseWallet } from '@web3-react/coinbase-wallet'


const RPC_URLS = Chains.list()
.map((x) => {
const id = Chains.get(x).id;
Expand All @@ -17,23 +20,63 @@ const RPC_URLS = Chains.list()
});
RPC_URLS[1] = process.env.infura;

export const injected = new InjectedConnector({
supportedChainIds: Chains.list().map((x) => Chains.get(x).id),
});

export const walletconnect = new WalletConnectConnector({
rpc: { 1: RPC_URLS[1] /*, 137: RPC_URLS[137]*/ }, // web3-react walletconnect connector not compatible
bridge: "https://bridge.walletconnect.org",
qrcode: true,
pollingInterval: POLLING_INTERVAL,
});

export const walletlink = new WalletLinkConnector({
url: RPC_URLS[1],
appName: "Pickle Finance",
appLogoUrl: "pickle.png",
});

export const cloverconnect = new CloverConnector({
supportedChainIds: [1],
});
export const [metaMask, metaMaskHooks] = initializeConnector<MetaMask>((actions) => new MetaMask(actions));

export const [walletConnect, walletConnectHooks] = initializeConnector<WalletConnect>(
(actions) =>
new WalletConnect(actions, {
rpc: RPC_URLS,
}),
Object.keys(RPC_URLS).map((chainId) => Number(chainId)),
);

export const [coinbaseWallet, coinbaseWalletHooks] = initializeConnector<CoinbaseWallet>(
(actions) =>
new CoinbaseWallet(actions, {
url: RPC_URLS[1][0],
appName: "Pickle Finance",
appLogoUrl: "pickle.png",
}),
);




export function getHooks(connector: Connector): Web3ReactHooks | undefined {
if (connector instanceof CoinbaseWallet) return coinbaseWalletHooks;
if (connector instanceof MetaMask) return metaMaskHooks;
if (connector instanceof WalletConnect) return walletConnectHooks;
}

export const connectorsAndHooks: [Connector, Web3ReactHooks][] = [
[metaMask, metaMaskHooks],
[walletConnect, walletConnectHooks],
[coinbaseWallet, coinbaseWalletHooks],
]

export const connectorItemPropsList = [
{
icon: "metamask.svg",
title: "connection.metamask", // translation string
connector: metaMask,
hooks: metaMaskHooks,
},
{
icon: "walletconnect.svg",
title: "connection.walletConnect", // translation string
connector: walletConnect,
hooks: walletConnectHooks,
},
{
icon: "coinbase.svg",
title: "connection.coinbase", // translation string
connector: coinbaseWallet,
hooks: coinbaseWalletHooks,
},
// {
// icon: "clover.svg",
// title: t("connection.clover"),
// connector: metaMask,
// hooks: metaMaskHooks,
// },
];
Loading