Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6993fd8

Browse files
Update get started docs (MetaMask#28)
* Update get started docs * Edits * Edits * Update instructions and integrate reviewer feedback * Clarifying edits * Apply suggestions from code review Co-authored-by: Byron Gravenorst <[email protected]> * Integrate reviewer feedback * include window.ethereum and change private argument --------- Co-authored-by: Byron Gravenorst <[email protected]>
1 parent 102751b commit 6993fd8

13 files changed

Lines changed: 483 additions & 622 deletions

wallet-sidebar.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ const sidebar = {
1111
collapsed: false,
1212
items: [
1313
"get-started/set-up-dev-environment",
14-
"get-started/run-test-network",
14+
"get-started/run-development-network",
1515
"get-started/detect-metamask",
16-
"get-started/access-account",
17-
"get-started/log-in-users",
16+
"get-started/detect-network",
17+
"get-started/access-accounts",
1818
],
1919
},
2020
{

wallet/get-started/access-account.md

Lines changed: 0 additions & 120 deletions
This file was deleted.
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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+
:::
Lines changed: 91 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,101 @@
1+
---
2+
description: Detect the MetaMask Ethereum provider object.
3+
---
4+
15
# Detect MetaMask
26

3-
To verify if the browser is running MetaMask, copy and paste the following code snippet in the
4-
developer console of your web browser:
7+
The presence of the MetaMask Ethereum provider object, `window.ethereum`, in a user's browser
8+
indicates an Ethereum user.
9+
10+
To demonstrate this, verify if your browser is running MetaMask by copying and pasting the following
11+
code snippet in the developer console of your browser:
512

613
```javascript
714
if (typeof window.ethereum !== 'undefined') {
815
console.log('MetaMask is installed!');
916
}
1017
```
1118

12-
View the [full API](../reference/provider-api.md) for the `window.ethereum` object.
19+
:::tip
20+
To differentiate MetaMask from other Ethereum-compatible browsers, you can detect MetaMask using the
21+
[`ethereum.isMetaMask`](../reference/provider-api.md#ethereumismetamask) property.
22+
:::
23+
24+
## Use @metamask/detect-provider
25+
26+
We recommend using the [`@metamask/detect-provider`](https://github.com/MetaMask/detect-provider)
27+
module to detect the MetaMask Ethereum provider on any platform or browser.
28+
29+
Use [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to install
30+
`@metamask/detect-provider` in your project directory:
31+
32+
```bash
33+
npm i @metamask/detect-provider
34+
```
35+
36+
In the [example project script](set-up-dev-environment.md#example), the following code detects the
37+
provider using `@metamask/detect-provider`:
38+
39+
```javascript title="index.js"
40+
// This function detects most providers injected at window.ethereum.
41+
import detectEthereumProvider from '@metamask/detect-provider';
42+
43+
// This returns the provider, or null if it wasn't detected.
44+
const provider = await detectEthereumProvider();
45+
46+
if (provider) {
47+
// From now on, this should always be true:
48+
// provider === window.ethereum
49+
startApp(provider); // initialize your app
50+
} else {
51+
console.log('Please install MetaMask!');
52+
}
53+
54+
function startApp(provider) {
55+
// If the provider returned by detectEthereumProvider isn't the same as
56+
// window.ethereum, something is overwriting it – perhaps another wallet.
57+
if (provider !== window.ethereum) {
58+
console.error('Do you have multiple wallets installed?');
59+
}
60+
// Access the decentralized web!
61+
}
62+
```
63+
64+
### Compile the module
65+
66+
Use a bundler such as [Webpack](https://github.com/webpack/webpack) to compile the module and create
67+
an output script.
68+
Install Webpack in your project directory:
69+
70+
```bash
71+
npm i --save-dev webpack
72+
```
73+
74+
Install the Webpack CLI:
75+
76+
```bash
77+
npm i --save-dev webpack-cli
78+
```
79+
80+
Compile the module:
81+
82+
```bash
83+
npx webpack
84+
```
85+
86+
:::note
87+
When compiling the module, you might need to pass CLI options such as
88+
[`--experiments-top-level-await`](https://webpack.js.org/configuration/experiments/).
89+
You can alternatively specify options in a configuration file as follows:
90+
91+
```javascript title="webpack.config.cjs"
92+
module.exports = {
93+
experiments: {
94+
topLevelAwait: true,
95+
},
96+
};
97+
```
98+
:::
1399

14-
To differentiate MetaMask from other Ethereum-compatible browsers, you can detect MetaMask using
15-
`ethereum.isMetaMask`.
100+
Run `npx webpack` again upon any changes to `index.js`.
101+
See [Webpack's Getting Started guide](https://webpack.js.org/guides/getting-started/) for more information.

0 commit comments

Comments
 (0)