on master help sign in
metamask: resolve connected accounts

This change adds the recommended approach to get a user's connected account address, as well as fallbacks for older versions of Metamask. This resolves #1073 See: https://docs.metamask.io/guide/sending-transactions.html#example https://metamask.zendesk.com/hc/en-us/articles/360053147012-MetaMask-Legacy-Web3

commite47013d7876a3567694b839cd55ca668d0613352 authortomholford <tomholford@users.noreply.github.com> dateThu 17 Nov 2022, 06:47 (4 years ago) parent13cfe28
2 files changed+15−5
src/lib/metamask.ts+14−5 src/react-app-env.d.ts+1
src/lib/metamask.ts+14−5
@@ -18,13 +18,22 @@ 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) {
23− throw new Error('No accounts connected');
21+ let from = null;
22+ if(window.ethereum) {
23+ from = window.ethereum.selectedAddress;
24+ if (!from) {
25+ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
26+ from = accounts[0] ?? null;
27+ }
28+ } else if (window.web3) {
29+ from = window.web3?.eth?.defaultAccount ?? null;
30+ } else {
31+ const accounts = await web3.eth.getAccounts();
32+ from = accounts[0] ?? null;
2433 }
25− const from = accounts[0];
34+
2635 const { data, to, value, maxPriorityFeePerGas, maxFeePerGas } = txn.toJSON();
27− if (!(data && to && value && maxPriorityFeePerGas && maxFeePerGas && from)) { // TODO
36+ if (!(data && to && value && maxPriorityFeePerGas && maxFeePerGas && from)) {
2837 throw new Error('Unable to send Metamask TX, something is missing');
2938 }
3039
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}