-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmetamask-connector.ts
More file actions
341 lines (324 loc) · 11.9 KB
/
Copy pathmetamask-connector.ts
File metadata and controls
341 lines (324 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* eslint-disable @typescript-eslint/explicit-function-return-type -- Wagmi connector API */
/* eslint-disable no-restricted-globals -- Browser connector uses window */
/* eslint-disable @typescript-eslint/no-misused-promises -- Event handlers are async */
/* eslint-disable require-atomic-updates -- Race conditions are acceptable for caching */
/* eslint-disable id-denylist -- 'err' is clear in catch context */
/* eslint-disable id-length -- 'x' is clear in lambda context */
/* eslint-disable @typescript-eslint/no-shadow -- accounts shadow is intentional */
/* eslint-disable no-nested-ternary -- Ternary chain is clearer here */
/* eslint-disable jsdoc/require-param-description -- Wagmi connector API */
/* eslint-disable jsdoc/require-returns -- Wagmi connector API */
/* eslint-disable @typescript-eslint/no-non-null-assertion -- Provider is guaranteed after check */
import type {
createEVMClient,
EIP1193Provider,
MetamaskConnectEVM,
} from '@metamask/connect-evm';
import { ChainNotConfiguredError, createConnector } from '@wagmi/core';
import type { ExactPartial, OneOf, UnionCompute } from '@wagmi/core/internal';
import {
type Address,
getAddress,
numberToHex,
type ProviderConnectInfo,
ResourceUnavailableRpcError,
type RpcError,
SwitchChainError,
UserRejectedRequestError,
withRetry,
withTimeout,
} from 'viem';
export type MetaMaskParameters = UnionCompute<
ExactPartial<Omit<CreateEVMClientParameters, 'api' | 'eventHandlers'>> & {
/** @deprecated use `dapp` instead */
dappMetadata?: CreateEVMClientParameters['dapp'];
/** @deprecated use `debug` instead */
logging?: unknown;
/** Mobile-specific options, including preferredOpenLink for React Native deeplinks */
mobile?: {
/** Custom function to open deeplinks - required for React Native since window.location.href doesn't work */
preferredOpenLink?: (deeplink: string, target?: string) => void;
/** Whether to use deeplink (default: true) or universal link */
useDeeplink?: boolean;
};
} & OneOf<
| {
/* Shortcut to connect and sign a message */
connectAndSign?: string | undefined;
}
| {
// TODO: Strongly type `method` and `params`
/* Allow `connectWith` any rpc method */
connectWith?: { method: string; params: unknown[] } | undefined;
}
>
>;
type CreateEVMClientParameters = Parameters<typeof createEVMClient>[0];
metaMask.type = 'metaMask' as const;
/**
*
* @param parameters
*/
export function metaMask(parameters: MetaMaskParameters = {}) {
type Provider = EIP1193Provider;
type Properties = {
onConnect(connectInfo: ProviderConnectInfo): void;
onDisplayUri(uri: string): void;
getInstance(): Promise<MetamaskConnectEVM>;
};
let metamask: MetamaskConnectEVM | undefined;
let metamaskPromise: Promise<MetamaskConnectEVM> | undefined;
return createConnector<Provider, Properties>((config) => ({
id: 'metaMaskSDK',
name: 'MetaMask',
rdns: ['io.metamask', 'io.metamask.mobile', 'io.metamask.flask'],
type: metaMask.type,
async connect({ chainId = 1, isReconnecting, withCapabilities } = {}) {
const instance = await this.getInstance();
const provider = instance.getProvider();
let accounts: readonly Address[] = [];
if (isReconnecting) {
accounts = await this.getAccounts().catch(() => []);
}
try {
let signResponse: string | undefined;
let connectWithResponse: unknown | undefined;
if (!accounts?.length) {
const chainIds = config.chains.map((chain) => numberToHex(chain.id));
if (parameters.connectAndSign || parameters.connectWith) {
if (parameters.connectAndSign) {
signResponse = (
await instance.connectAndSign({
chainIds,
message: parameters.connectAndSign,
})
).signature;
} else if (parameters.connectWith) {
connectWithResponse = (
await instance.connectWith({
chainIds,
method: parameters.connectWith.method,
params: parameters.connectWith.params,
})
).result;
}
accounts = await this.getAccounts();
} else {
const result = await instance.connect({ chainIds });
accounts = result.accounts.map((x) => getAddress(x));
}
}
// Switch to chain if provided
let currentChainId = await this.getChainId();
if (chainId && currentChainId !== chainId) {
const chain = await this.switchChain!({ chainId }).catch((error) => {
if (error.code === UserRejectedRequestError.code) {
throw error;
}
return { id: currentChainId };
});
currentChainId = chain?.id ?? currentChainId;
}
if (signResponse) {
provider.emit('connectAndSign', {
accounts,
chainId: numberToHex(currentChainId),
signature: signResponse,
});
} else if (connectWithResponse) {
provider.emit('connectWith', {
accounts,
chainId: numberToHex(currentChainId),
result: connectWithResponse,
});
}
return {
// TODO(v3): Make `withCapabilities: true` default behavior
accounts: (withCapabilities
? accounts.map((address) => ({ address, capabilities: {} }))
: accounts) as never,
chainId: currentChainId,
};
} catch (err) {
const error = err as RpcError;
if (error.code === UserRejectedRequestError.code) {
throw new UserRejectedRequestError(error);
}
if (error.code === ResourceUnavailableRpcError.code) {
throw new ResourceUnavailableRpcError(error);
}
throw error;
}
},
async disconnect() {
const instance = await this.getInstance();
return instance.disconnect();
},
async getAccounts() {
const instance = await this.getInstance();
if (instance.accounts.length) {
return instance.accounts.map((x) => getAddress(x));
}
// Fallback to provider if SDK doesn't return accounts
const provider = instance.getProvider();
const accounts = (await provider.request({
method: 'eth_accounts',
})) as string[];
return accounts.map((x) => getAddress(x));
},
async getChainId() {
const instance = await this.getInstance();
if (instance.getChainId()) {
return Number(instance.getChainId());
}
// Fallback to provider if SDK doesn't return chainId
const provider = instance.getProvider();
const chainId = await provider.request({ method: 'eth_chainId' });
return Number(chainId);
},
async getProvider() {
const instance = await this.getInstance();
return instance.getProvider();
},
async isAuthorized() {
try {
// MetaMask mobile provider sometimes fails to immediately resolve
// JSON-RPC requests on page load
const timeout = 10;
const accounts = await withRetry(
async () =>
withTimeout(
async () => {
const accounts = await this.getAccounts();
if (!accounts.length) {
throw new Error('try again');
}
return accounts;
},
{ timeout },
),
{ delay: timeout + 1, retryCount: 3 },
);
return Boolean(accounts.length);
} catch {
return false;
}
},
async switchChain({ addEthereumChainParameter, chainId }) {
const chain = config.chains.find(({ id }) => id === Number(chainId));
if (!chain) {
throw new SwitchChainError(new ChainNotConfiguredError());
}
const hexChainId = numberToHex(chainId);
try {
const instance = await this.getInstance();
await instance.switchChain({
chainId: hexChainId,
chainConfiguration: {
blockExplorerUrls: addEthereumChainParameter?.blockExplorerUrls
? [...addEthereumChainParameter.blockExplorerUrls]
: chain.blockExplorers?.default.url
? [chain.blockExplorers.default.url]
: undefined,
chainId: hexChainId,
chainName: addEthereumChainParameter?.chainName ?? chain.name,
iconUrls: addEthereumChainParameter?.iconUrls,
nativeCurrency:
addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency,
rpcUrls: addEthereumChainParameter?.rpcUrls
? [...addEthereumChainParameter.rpcUrls]
: chain.rpcUrls.default?.http
? [...chain.rpcUrls.default.http]
: undefined,
},
});
return chain;
} catch (err) {
const error = err as RpcError;
if (error.code === UserRejectedRequestError.code) {
throw new UserRejectedRequestError(error);
}
throw new SwitchChainError(error);
}
},
async onAccountsChanged(accounts) {
config.emitter.emit('change', {
accounts: accounts.map((account) => getAddress(account)),
});
},
onChainChanged(chain) {
const chainId = Number(chain);
config.emitter.emit('change', { chainId });
},
async onConnect(connectInfo) {
const accounts = await this.getAccounts();
if (accounts.length === 0) {
return;
}
const chainId = Number(connectInfo.chainId);
config.emitter.emit('connect', { accounts, chainId });
},
async onDisconnect(error) {
// If MetaMask emits a `code: 1013` error, wait for reconnection before disconnecting
// https://github.com/MetaMask/providers/pull/120
if (error && (error as RpcError<1013>).code === 1013) {
const provider = await this.getProvider();
if (provider && Boolean((await this.getAccounts()).length)) {
return;
}
}
config.emitter.emit('disconnect');
},
onDisplayUri(uri) {
config.emitter.emit('message', { type: 'display_uri', data: uri });
},
async getInstance() {
if (!metamask) {
if (!metamaskPromise) {
const { createEVMClient } = await (async () => {
try {
return import('@metamask/connect-evm');
} catch {
throw new Error('dependency "@metamask/connect-evm" not found');
}
})();
const defaultDappParams =
typeof window === 'undefined'
? { name: 'wagmi' }
: {
name: window.location.hostname,
url: window.location.href,
};
metamaskPromise = createEVMClient({
...parameters,
skipAutoAnnounce: parameters.skipAutoAnnounce ?? true,
api: {
supportedNetworks: Object.fromEntries(
config.chains.map((chain) => [
numberToHex(chain.id),
chain.rpcUrls.default?.http[0] ?? '',
]),
),
},
dapp:
parameters.dappMetadata ?? parameters.dapp ?? defaultDappParams,
debug: parameters.logging ? true : parameters.debug,
eventHandlers: {
accountsChanged: this.onAccountsChanged.bind(this),
chainChanged: this.onChainChanged.bind(this),
connect: this.onConnect.bind(this),
disconnect: this.onDisconnect.bind(this),
displayUri: this.onDisplayUri.bind(this),
},
analytics: {
integrationType: 'wagmi',
},
...(parameters.mobile && { mobile: parameters.mobile }),
});
}
metamask = await metamaskPromise;
}
return metamask;
},
}));
}