on master help sign in
Merge pull request #1075 from urbit/t/1073-metamask-no-connected-accounts

metamask: resolve connected accounts

commit22e3d3a59eb79ab96ff51ccefb75f39222389661 authortomholford <16504501+tomholford@users.noreply.github.com> dateMon 21 Nov 2022, 22:25 (4 years ago) parent13cfe28e5e005a
2 files changed+22−4
src/lib/metamask.ts+21−4 src/react-app-env.d.ts+1
src/lib/metamask.ts+21−4
@@ -18,13 +18,30 @@ export const metamaskSignTransaction = async (txn: EIP1559Transaction) => {
1818};
1919
2020const metamaskSendTransaction = async (txn: FakeSignableTx, web3: Web3) => {
21− const accounts = await web3.eth.getAccounts();
22− if(accounts.length === 0) {
21+ /**
22+ * Depending which version of Metamask is installed, there are different
23+ * approaches to get the `from` address.
24+ */
25+ let from = null;
26+ if (window.ethereum) {
27+ from = window.ethereum.selectedAddress;
28+ if (!from) {
29+ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
30+ from = accounts[0] ?? null;
31+ }
32+ } else if (window.web3) {
33+ from = window.web3?.eth?.defaultAccount ?? null;
34+ } else {
35+ const accounts = await web3.eth.getAccounts();
36+ from = accounts[0] ?? null;
37+ }
38+
39+ if (!from) {
2340 throw new Error('No accounts connected');
2441 }
25− const from = accounts[0];
42+
2643 const { data, to, value, maxPriorityFeePerGas, maxFeePerGas } = txn.toJSON();
27− if (!(data && to && value && maxPriorityFeePerGas && maxFeePerGas && from)) { // TODO
44+ if (!(data && to && value && maxPriorityFeePerGas && maxFeePerGas && from)) {
2845 throw new Error('Unable to send Metamask TX, something is missing');
2946 }
3047
src/react-app-env.d.ts+1
@@ -3,4 +3,5 @@ declare module 'folktale/maybe';
33
44interface Window {
55 ethereum: any;
6+ web3?: any;
67}