Skip to content

Commit 151e759

Browse files
committed
update troubleshoot sections
1 parent 8e467fa commit 151e759

File tree

1 file changed

+83
-136
lines changed

1 file changed

+83
-136
lines changed

wallet/how-to/use-non-evm-networks/starknet/troubleshoot.md

Lines changed: 83 additions & 136 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ sidebar_position: 7
55

66
# Troubleshoot
77

8-
Use this guide to resolve common issues when connecting to MetaMask and using the Starknet Snap.
8+
This guide addresses issues that might occur when configuring the MetaMask connection or implementing the Starknet Snap.
99

10-
## Connection issus
10+
## Connection issues
1111

1212
When using `get-starknet`, the library automatically handles MetaMask detection, connection, and Starknet Snap installation.
1313
If you're using `wallet_invokeSnaps` directly, you might need to manage these processes manually.
@@ -23,7 +23,38 @@ async function detectMetamaskSupport(windowObject: Window & typeof globalThis):
2323
}
2424
```
2525

26-
This function uses the `waitForMetaMaskProvider` helper function, which attempts to detect the MetaMask provider up to three times.
26+
This function uses the `waitForMetaMaskProvider` helper function, which attempts to detect the MetaMask provider three times.
27+
28+
In the event MetaMask is not installed, for example `isMetaMaskInstallRequired=true`, you can prompt the user to install MetaMask.
29+
30+
```typescript
31+
function checkAndPromptForMetaMask() {
32+
const isMetaMaskInstalled = typeof window.ethereum !== 'undefined' && window.ethereum.isMetaMask;
33+
34+
if (!isMetaMaskInstalled) {
35+
console.log("MetaMask is not installed. Prompting user to install.");
36+
37+
// Update UI to inform the user.
38+
const messageElement = document.getElementById('metamask-message') || document.createElement('div');
39+
messageElement.id = 'metamask-message';
40+
messageElement.innerHTML = `
41+
<p>MetaMask is required to use this application. Please install MetaMask to continue.</p>
42+
<button id="install-metamask">Install MetaMask</button>
43+
`;
44+
document.body.appendChild(messageElement);
45+
46+
// Add click event to the install button.
47+
document.getElementById('install-metamask').addEventListener('click', () => {
48+
window.open('https://metamask.io/download.html', '_blank');
49+
});
50+
} else {
51+
console.log("MetaMask is installed. Proceeding with application.");
52+
}
53+
}
54+
55+
// Call this function when your application initializes.
56+
checkAndPromptForMetaMask();
57+
```
2758

2859
### Verify Snap support
2960

@@ -42,13 +73,56 @@ const isSupportSnap = async (provider: any): Promise<boolean> => {
4273
};
4374
```
4475

45-
### Helper Functions
76+
If MetaMask is installed but the Snap is not, use the following code to prompt the user to install the Snap:
77+
78+
```typescript
79+
async function installSnap(provider: MetaMaskProvider, snapId: string, snapVersion: string) {
80+
try {
81+
await provider.request({
82+
method: 'wallet_requestSnaps',
83+
params: {
84+
[snapId]: { version: snapVersion },
85+
},
86+
});
87+
console.log('Snap installed successfully');
88+
} catch (error) {
89+
console.error('Failed to install Snap:', error);
90+
// Handle the error (for example, user rejected installation).
91+
}
92+
}
93+
```
94+
95+
### Handle user rejection
4696

47-
The following helper functions support the detection process:
97+
Users can reject the prompt to add the Snap, resulting in a 4001 error.
98+
You can provide an error message to ensure users have clear guidance on next steps.
99+
100+
```javascript
101+
function handleConnectionError(error) {
102+
if (error.code === 4001) {
103+
console.log('User rejected the request to add the Starknet Snap');
104+
displayUserMessage("To proceed, you need to add the Starknet Snap to MetaMask. Please try connecting again.");
105+
} else {
106+
console.error('An error occurred while connecting to Starknet Snap:', error);
107+
displayUserMessage("An error occurred. Please ensure MetaMask is installed and try again.");
108+
}
109+
}
110+
111+
function displayUserMessage(message) {
112+
// Update your UI to display the message to the user
113+
// For example:
114+
// document.getElementById('status-message').textContent = message;
115+
}
116+
```
117+
118+
### Helper functions
119+
120+
The following helper functions support the detection process.
121+
This is useful for troubleshooting issues that might occur when using the 'wallet_invokeSnap` method.
48122

49123
#### `isMetaMaskProvider`
50124

51-
This type guard function checks if a given object is a valid MetaMaskProvider:
125+
The following function checks if a given object is a valid `MetaMaskProvider`:
52126

53127
```typescript
54128
function isMetaMaskProvider(obj: unknown): obj is MetaMaskProvider {
@@ -63,151 +137,24 @@ function isMetaMaskProvider(obj: unknown): obj is MetaMaskProvider {
63137

64138
### `detectMetaMaskProvider`
65139

66-
This function detects a MetaMask provider by listening for the `eip6963:announceProvider` event:
140+
The following function detects a MetaMask provider by listening for the `eip6963:announceProvider` event:
67141

68-
```typescrip
142+
```typescript
69143
function detectMetaMaskProvider(
70144
windowObject: Window & typeof globalThis,
71145
{ timeout = 3000 } = {},
72146
): Promise<MetaMaskProvider | null> {
73-
// ... (function implementation)
74147
}
75148
```
76149

77150
### `waitForMetaMaskProvider`
78151

79-
This function waits for a MetaMask provider to be detected and retrys if necessary:
152+
The following function waits for a MetaMask provider to be detected and retrys the operation if needed:
80153

81154
```typescript
82155
async function waitForMetaMaskProvider(
83156
windowObject: Window & typeof globalThis,
84157
{ timeout = 1000, retries = 0 } = {},
85158
): Promise<MetaMaskProvider | null> {
86-
// ... (function implementation)
87-
}
88-
```
89-
90-
## Types and Interfaces
91-
92-
```typescript
93-
interface MetaMaskProvider {
94-
isMetaMask: boolean;
95-
request(options: { method: string }): Promise<void>;
96-
}
97-
98-
declare global {
99-
interface Window {
100-
ethereum?: MetaMaskProvider;
101-
}
102159
}
103160
```
104-
105-
## Best Practices
106-
107-
1. Always check for MetaMask installation before attempting to use Snap functionality.
108-
2. Handle cases where MetaMask is not installed or doesn't support Snaps gracefully.
109-
3. Provide clear feedback to users if MetaMask or Snap support is missing.
110-
4. Consider implementing a retry mechanism for provider detection to account for potential timing issues.
111-
112-
By following these steps and using the provided functions, you can reliably detect MetaMask and verify Snap support in your application.
113-
114-
115-
This can be used as follow to check for Metamask Snap Support. This will check for MetaMask presence, and the support of Snap in the installed MetaMask version if any. If there is no MetaMask installed or the version of MetaMask does not support snap
116-
117-
```typescript
118-
let isMetaMaskInstallRequired = false;
119-
let provider = null;
120-
try {
121-
provider = await detectMetamaskSupport(window);
122-
// Use the new detection method
123-
124-
if (provider && (await isSupportSnap(provider))) {
125-
isMetaMaskInstallRequired = provider === null;
126-
} else {
127-
isMetaMaskInstallRequired = true;
128-
}
129-
} catch (err) {
130-
isMetaMaskInstallRequired = true;
131-
}
132-
```
133-
134-
In case MetaMask is not installed (e.g. `isMetaMaskInstallRequired=true` we can prompt the user to install MetaMask.
135-
136-
In case MetaMask is installed, we can prompt the user to install the Snap
137-
138-
```typescript
139-
provider
140-
.request({
141-
method: 'wallet_requestSnaps',
142-
params: {
143-
[snapId]: { version: snapVersion },
144-
},
145-
})
146-
.then(() => {
147-
// The snap has been installed proceed accordingly.
148-
})
149-
.catch(() => {
150-
// The snap has not been installed (user rejected the installation)
151-
});
152-
```
153-
## Snap permissions
154-
155-
### Snap is not properly approved.
156-
157-
Guide users through the process of approving the Snap in MetaMask. If they deny the connection, provide a retry option.
158-
159-
### Snap ID error
160-
161-
Ensure you're using the correct Snap ID for the StarkNet Snap. Incorrect IDs will result in failed connections.
162-
The Starknet Snap ID is the name of the npm package of the snap: `@consensys/starknet-snap`.
163-
164-
165-
## Best practices
166-
167-
### 1. Graceful error handling
168-
169-
Provide clear feedback to the user, such as offering a retry option or showing a message that StarkNet Snap needs to be installed.
170-
171-
```javascript
172-
const handleConnect = async () => {
173-
try {
174-
const res = await connect();
175-
if (!res) {
176-
console.log('No wallet connected');
177-
}
178-
} catch (error) {
179-
console.error('Failed to connect to wallet:', error);
180-
alert('An error occurred while connecting to the wallet. Please try again.');
181-
}
182-
};
183-
```
184-
185-
### 2. Detect and Handle account changes
186-
187-
Ensure that you detect when the user switches accounts or changes networks. MetaMask emits events like `accountsChanged` and `chainChanged` that you can listen for and handle appropriately.
188-
189-
```javascript
190-
window.ethereum.on('accountsChanged', (accounts) => {
191-
console.log('Accounts changed:', accounts);
192-
// Update the UI or re-fetch account data
193-
});
194-
195-
window.ethereum.on('chainChanged', (chainId) => {
196-
console.log('Network changed:', chainId);
197-
// Handle network change
198-
});
199-
```
200-
201-
### 3. Support for multiple wallets
202-
203-
`get-starknet` supports connecting to multiple wallets. Provide users with options to select the wallet they want to connect, if applicable. You can specify wallet options when calling connect().
204-
205-
```javascript
206-
const handleConnect = async () => {
207-
const options = {
208-
modalMode: 'alwaysAsk', // Force the wallet selection modal to appear
209-
};
210-
const res = await connect(options);
211-
console.log('Connected to wallet:', res?.name);
212-
};
213-
```

0 commit comments

Comments
 (0)