-
Notifications
You must be signed in to change notification settings - Fork 480
Expand file tree
/
Copy pathWeb3Provider.tsx
More file actions
262 lines (233 loc) · 8.62 KB
/
Web3Provider.tsx
File metadata and controls
262 lines (233 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import { API_ETH_MOCK_ADDRESS, ERC20Service, transactionType } from '@aave/contract-helpers';
import { SignatureLike } from '@ethersproject/bytes';
import { JsonRpcProvider, TransactionResponse } from '@ethersproject/providers';
import { BigNumber, PopulatedTransaction, utils } from 'ethers';
import React, { ReactElement, useEffect, useState } from 'react';
import { useIsContractAddress } from 'src/hooks/useIsContractAddress';
import { useRootStore } from 'src/store/root';
import { wagmiConfig } from 'src/ui-config/wagmiConfig';
import { hexToAscii } from 'src/utils/utils';
import { UserRejectedRequestError } from 'viem';
import { useAccount, useConnect, useSwitchChain, useWatchAsset } from 'wagmi';
import { useShallow } from 'zustand/shallow';
import { Web3Context } from '../hooks/useWeb3Context';
import { getEthersProvider } from './adapters/EthersAdapter';
export type ERC20TokenType = {
address: string;
symbol: string;
decimals: number;
image?: string;
aToken?: boolean;
};
export type Web3Data = {
currentAccount: string;
chainId: number;
switchNetwork: (chainId: number) => Promise<void>;
getTxError: (txHash: string) => Promise<string>;
sendTx: (txData: transactionType | PopulatedTransaction) => Promise<TransactionResponse>;
addERC20Token: (args: ERC20TokenType) => Promise<boolean>;
signTxData: (unsignedData: string) => Promise<SignatureLike>;
switchNetworkError: Error | undefined;
setSwitchNetworkError: (err: Error | undefined) => void;
readOnlyMode: boolean;
readOnlyModeAddress: string | undefined;
provider: JsonRpcProvider | undefined;
setReadOnlyModeAddress: (address: string | undefined) => void;
};
let didInit = false;
let didAutoConnectForCypress = false;
export const Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
const { switchChainAsync } = useSwitchChain();
const { watchAssetAsync } = useWatchAsset();
const { chainId, address } = useAccount();
const { connect, connectors } = useConnect();
const [readOnlyModeAddress, setReadOnlyModeAddress] = useState<string | undefined>();
const [switchNetworkError, setSwitchNetworkError] = useState<Error>();
const [setAccount, setConnectedAccountIsContract] = useRootStore(
useShallow((store) => [store.setAccount, store.setConnectedAccountIsContract])
);
const account = address;
const readOnlyMode = utils.isAddress(readOnlyModeAddress || '');
let currentAccount = account?.toLowerCase() || '';
if (readOnlyMode && readOnlyModeAddress) {
currentAccount = readOnlyModeAddress;
}
const { data: isContractAddress } = useIsContractAddress(account || '', chainId);
useEffect(() => {
if (didInit) {
return;
}
// If the app loads in readOnlyMode, then we disconnect the wallet if it auto connected
const storedReadOnlyAddress = localStorage.getItem('readOnlyModeAddress');
if (storedReadOnlyAddress && utils.isAddress(storedReadOnlyAddress)) {
setReadOnlyModeAddress(storedReadOnlyAddress);
}
didInit = true;
}, [readOnlyMode]);
useEffect(() => {
// If running cypress tests, then we try to auto connect on app load
// so it doesn't have to be driven through the UI.
const isCypressEnabled = process.env.NEXT_PUBLIC_IS_CYPRESS_ENABLED === 'true';
if (!isCypressEnabled || didAutoConnectForCypress) {
return;
}
const injected = connectors[0];
connect({ connector: injected });
didAutoConnectForCypress = true;
}, [connect, connectors]);
const sendTx = async (
txData: transactionType | PopulatedTransaction
): Promise<TransactionResponse> => {
const provider = await getEthersProvider(wagmiConfig, { chainId });
if (provider) {
const { from, ...data } = txData;
const signer = provider.getSigner(from);
try {
const txResponse: TransactionResponse = await signer.sendTransaction({
...data,
value: data.value ? BigNumber.from(data.value) : undefined,
});
return txResponse;
} catch (error) {
// Ethers.js incompatibility with Smart Account ERC-20 paymasters
// Transaction may succeed on-chain but fail to return proper response
if (error.transactionHash) {
const hash = error.transactionHash;
try {
const receipt = await provider.getTransactionReceipt(hash);
if (receipt) {
const confirmedReceipt = await provider.waitForTransaction(hash, 2);
return {
hash: hash,
nonce: confirmedReceipt.transactionIndex,
gasLimit: confirmedReceipt.gasUsed,
gasPrice: confirmedReceipt.effectiveGasPrice,
data: data.data || '0x',
value: data.value ? BigNumber.from(data.value) : BigNumber.from(0),
chainId: chainId,
confirmations: confirmedReceipt.confirmations,
from: confirmedReceipt.from,
blockNumber: confirmedReceipt.blockNumber,
blockHash: confirmedReceipt.blockHash,
wait: async (confirmations?: number) => {
if (!confirmations || confirmations <= 1) {
return receipt;
}
return await provider.waitForTransaction(hash, confirmations);
},
} as TransactionResponse;
}
throw new Error(`Transaction not found: ${hash}`);
} catch (receiptError) {
throw new Error(`Could not verify transaction: ${hash}`);
}
}
throw new Error(error.message || 'Transaction failed');
}
}
throw new Error('Error sending transaction. Provider not found');
};
const signTxData = async (unsignedData: string): Promise<SignatureLike> => {
const provider = await getEthersProvider(wagmiConfig, { chainId });
if (provider && account) {
const signature: SignatureLike = await provider.send('eth_signTypedData_v4', [
account,
unsignedData,
]);
return signature;
}
throw new Error('Error initializing permit signature');
};
const switchNetwork = async (newChainId: number) => {
try {
await switchChainAsync({ chainId: newChainId });
setSwitchNetworkError(undefined);
} catch (switchError) {
if (switchError.code === UserRejectedRequestError.code) {
setSwitchNetworkError(switchError);
} else {
setSwitchNetworkError(undefined);
}
}
};
const getTxError = async (txHash: string): Promise<string> => {
const provider = await getEthersProvider(wagmiConfig, { chainId });
if (provider) {
const tx = await provider.getTransaction(txHash);
// @ts-expect-error TODO: need think about "tx" type
const code = await provider.call(tx, tx.blockNumber);
const error = hexToAscii(code.substr(138));
return error;
}
throw new Error('Error getting transaction. Provider not found');
};
const addERC20Token = async ({
address,
symbol,
decimals,
image,
}: ERC20TokenType): Promise<boolean> => {
const provider = await getEthersProvider(wagmiConfig, { chainId });
if (provider) {
if (address.toLowerCase() !== API_ETH_MOCK_ADDRESS.toLowerCase()) {
let tokenSymbol = symbol;
if (!tokenSymbol) {
const { getTokenData } = new ERC20Service(provider);
const { symbol } = await getTokenData(address);
tokenSymbol = symbol;
}
await watchAssetAsync({
type: 'ERC20',
options: {
address,
symbol: tokenSymbol,
decimals,
image,
},
});
return true;
}
}
return false;
};
useEffect(() => {
setAccount(account?.toLowerCase());
}, [account, setAccount]);
useEffect(() => {
if (readOnlyModeAddress) {
setAccount(readOnlyModeAddress.toLowerCase());
}
}, [readOnlyModeAddress, setAccount]);
useEffect(() => {
if (!account) {
setConnectedAccountIsContract(false);
return;
}
if (isContractAddress) {
setConnectedAccountIsContract(true);
}
}, [isContractAddress, setConnectedAccountIsContract, account]);
return (
<Web3Context.Provider
value={{
web3ProviderData: {
chainId: chainId || 1,
switchNetwork,
getTxError,
sendTx,
signTxData,
currentAccount,
addERC20Token,
switchNetworkError,
setSwitchNetworkError,
readOnlyMode,
provider: undefined,
readOnlyModeAddress,
setReadOnlyModeAddress,
},
}}
>
{children}
</Web3Context.Provider>
);
};