|
| 1 | +--- |
| 2 | +description: Access a user's accounts and handle changed accounts. |
| 3 | +--- |
| 4 | + |
| 5 | +import Tabs from '@theme/Tabs'; |
| 6 | +import TabItem from '@theme/TabItem'; |
| 7 | + |
| 8 | +# Access a user's accounts |
| 9 | + |
| 10 | +User accounts are used in a variety of contexts in Ethereum, including as identifiers and for |
| 11 | +signing transactions. |
| 12 | +To request a signature from a user or have a user approve a transaction, your dapp must |
| 13 | +access the user's accounts using the |
| 14 | +[`eth_requestAccounts`](../reference/rpc-api.md#ethereum-json-rpc-methods) RPC method. |
| 15 | + |
| 16 | +When accessing a user's accounts: |
| 17 | + |
| 18 | +- **Only** initiate a connection request in response to direct user action, such as |
| 19 | + selecting a [connect button](#create-a-connect-button). |
| 20 | +- **Always** disable the connect button while the connection request is pending. |
| 21 | +- **Never** initiate a connection request on page load. |
| 22 | + |
| 23 | +:::tip |
| 24 | +You can also [use MetaMask SDK](../how-to/use-sdk/index.md) to enable a reliable, secure, and |
| 25 | +seamless connection from your dapp to a MetaMask wallet client. |
| 26 | +::: |
| 27 | + |
| 28 | +## Create a connect button |
| 29 | + |
| 30 | +We recommend providing a button to allow users to connect MetaMask to your dapp. |
| 31 | +Selecting this button should call `eth_requestAccounts` to access the user's account. |
| 32 | + |
| 33 | +In the [example project code](set-up-dev-environment.md#example), the following JavaScript code |
| 34 | +accesses the user's accounts when they select a connect button, and the following HTML code |
| 35 | +displays the button and the current account: |
| 36 | + |
| 37 | +<Tabs> |
| 38 | +<TabItem value="javascript" label="JavaScript"> |
| 39 | + |
| 40 | +```javascript title="index.js" |
| 41 | +// You should only attempt to request the user's account in response to user |
| 42 | +// interaction, such as selecting a button. |
| 43 | +// Otherwise, you popup-spam the user like it's 1999. |
| 44 | +// If you fail to retrieve the user's account, you should encourage the user |
| 45 | +// to initiate the attempt. |
| 46 | +const ethereumButton = document.querySelector('.enableEthereumButton'); |
| 47 | +const showAccount = document.querySelector('.showAccount'); |
| 48 | + |
| 49 | +ethereumButton.addEventListener('click', () => { |
| 50 | + getAccount(); |
| 51 | +}); |
| 52 | + |
| 53 | +// While awaiting the call to eth_requestAccounts, you should disable |
| 54 | +// any buttons the user can select to initiate the request. |
| 55 | +// MetaMask rejects any additional requests while the first is still |
| 56 | +// pending. |
| 57 | +async function getAccount() { |
| 58 | + const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) |
| 59 | + .catch((err) => { |
| 60 | + if (err.code === 4001) { |
| 61 | + // EIP-1193 userRejectedRequest error |
| 62 | + // If this happens, the user rejected the connection request. |
| 63 | + console.log('Please connect to MetaMask.'); |
| 64 | + } else { |
| 65 | + console.error(err); |
| 66 | + } |
| 67 | + }); |
| 68 | + const account = accounts[0]; |
| 69 | + showAccount.innerHTML = account; |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +</TabItem> |
| 74 | +<TabItem value="html" label="HTML"> |
| 75 | + |
| 76 | +```html title="index.html" |
| 77 | +<!-- Display a connect button and the current account --> |
| 78 | +<button class="enableEthereumButton">Enable Ethereum</button> |
| 79 | +<h2>Account: <span class="showAccount"></span></h2> |
| 80 | +``` |
| 81 | + |
| 82 | +</TabItem> |
| 83 | +</Tabs> |
| 84 | + |
| 85 | +## Handle accounts |
| 86 | + |
| 87 | +Use the [`eth_accounts`](https://metamask.github.io/api-playground/api-documentation/#eth_accounts) |
| 88 | +RPC method to handle user accounts. |
| 89 | +Subscribe to the [`accountsChanged`](../reference/provider-api.md#accountschanged) provider event to |
| 90 | +be notified when the user changes accounts. |
| 91 | + |
| 92 | +In the [example project script](set-up-dev-environment.md#example), the following code handles user |
| 93 | +accounts and detects when the user changes accounts: |
| 94 | + |
| 95 | +```javascript title="index.js" |
| 96 | +let currentAccount = null; |
| 97 | +window.ethereum.request({ method: 'eth_accounts' }) |
| 98 | + .then(handleAccountsChanged) |
| 99 | + .catch((err) => { |
| 100 | + // Some unexpected error. |
| 101 | + // For backwards compatibility reasons, if no accounts are available, |
| 102 | + // eth_accounts returns an empty array. |
| 103 | + console.error(err); |
| 104 | + }); |
| 105 | + |
| 106 | +// Note that this event is emitted on page load. |
| 107 | +// If the array of accounts is non-empty, you're already |
| 108 | +// connected. |
| 109 | +window.ethereum.on('accountsChanged', handleAccountsChanged); |
| 110 | + |
| 111 | +// eth_accounts always returns an array. |
| 112 | +function handleAccountsChanged(accounts) { |
| 113 | + if (accounts.length === 0) { |
| 114 | + // MetaMask is locked or the user has not connected any accounts. |
| 115 | + console.log('Please connect to MetaMask.'); |
| 116 | + } else if (accounts[0] !== currentAccount) { |
| 117 | + // Reload your interface with accounts[0]. |
| 118 | + currentAccount = accounts[0]; |
| 119 | + // Update the account displayed (see the HTML for the connect button) |
| 120 | + showAccount.innerHTML = currentAccount; |
| 121 | + } |
| 122 | +} |
| 123 | +``` |
| 124 | + |
| 125 | +:::note |
| 126 | +In the future, the accounts array may contain more than one account. |
| 127 | +This functionality isn't available yet. |
| 128 | +The first account in the array will always be considered the user's "selected" account. |
| 129 | +::: |
0 commit comments