@dynamic-labs/starknet 3.0.0-alpha.5 → 3.0.0-alpha.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,8 @@ class StarknetWalletConnector extends walletConnectorCore.WalletConnectorBase {
22
22
  this.connectedChain = 'STARK';
23
23
  this.supportedChains = ['STARK'];
24
24
  this.switchNetworkOnlyFromWallet = true;
25
+ // required for metamask snap integration as MM snaps don't have event listeners
26
+ this.canSetEventListeners = true;
25
27
  this.name = name;
26
28
  this.windowKey = windowKey;
27
29
  this.starknetNetworks = opts.starknetNetworks;
@@ -91,7 +93,8 @@ class StarknetWalletConnector extends walletConnectorCore.WalletConnectorBase {
91
93
  if (!this.isInstalledOnBrowser() &&
92
94
  utils.isMobile() &&
93
95
  this.walletBookWallet.mobile &&
94
- this.walletBookWallet.mobile.inAppBrowser) {
96
+ this.walletBookWallet.mobile.inAppBrowser &&
97
+ this.mobileExperience === 'in-app-browser') {
95
98
  const inAppBrowserCompiledTemplate = utils.template(this.walletBookWallet.mobile.inAppBrowser);
96
99
  const deepLink = inAppBrowserCompiledTemplate({
97
100
  encodedDappURI: encodeURIComponent(window.location.toString()),
@@ -131,17 +134,16 @@ class StarknetWalletConnector extends walletConnectorCore.WalletConnectorBase {
131
134
  return signature === null || signature === void 0 ? void 0 : signature.join(',');
132
135
  });
133
136
  }
134
- getBalance() {
137
+ getBalance(address) {
135
138
  return _tslib.__awaiter(this, void 0, void 0, function* () {
136
- const walletAddress = yield this.getAddress();
137
139
  const provider = yield this.getWalletClient();
138
- if (!walletAddress || !provider) {
139
- walletConnectorCore.logger.error('Could not fetch wallet address for getting balance');
140
+ if (!provider) {
141
+ walletConnectorCore.logger.error('Could not find provider for getting balance');
140
142
  return undefined;
141
143
  }
142
144
  const contract = new starknet.Contract(ethereumContractAbi, constants.ETH_STARKNET_ADDRESS, provider);
143
145
  try {
144
- const { balance } = yield contract.balanceOf(walletAddress);
146
+ const { balance } = yield contract.balanceOf(address);
145
147
  /**
146
148
  * Dividing by 1e18 as the returned balance is a Gwei number.
147
149
  * Read more here: https://www.investopedia.com/terms/g/gwei-ethereum.asp#toc-what-is-gwei
@@ -182,6 +184,24 @@ class StarknetWalletConnector extends walletConnectorCore.WalletConnectorBase {
182
184
  if (!wallet) {
183
185
  return [];
184
186
  }
187
+ try {
188
+ yield this.reconnectIfNeeded(wallet);
189
+ }
190
+ catch (e) {
191
+ return [];
192
+ }
193
+ const getSelectedAddress = () => wallet.selectedAddress
194
+ ? Promise.resolve([wallet.selectedAddress])
195
+ : Promise.reject();
196
+ return utils.retryableFn(getSelectedAddress, {
197
+ fallbackValue: [],
198
+ retryIntervalMs: 100,
199
+ retryStrategy: 'timeout-and-rejection',
200
+ });
201
+ });
202
+ }
203
+ reconnectIfNeeded(wallet) {
204
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
185
205
  const needsReconnection = !this.isProviderConnected() && (yield wallet.isPreauthorized());
186
206
  if (needsReconnection) {
187
207
  /**
@@ -199,24 +219,18 @@ class StarknetWalletConnector extends walletConnectorCore.WalletConnectorBase {
199
219
  }
200
220
  catch (_a) {
201
221
  localStorage.removeItem('dynamic_should_have_wallet');
202
- return [];
222
+ throw new Error('Could not reconnect');
203
223
  }
204
224
  }
205
225
  else {
206
226
  yield this.connect();
207
227
  }
208
228
  }
209
- const getSelectedAddress = () => wallet.selectedAddress
210
- ? Promise.resolve([wallet.selectedAddress])
211
- : Promise.reject();
212
- return utils.retryableFn(getSelectedAddress, {
213
- fallbackValue: [],
214
- retryIntervalMs: 100,
215
- retryStrategy: 'timeout-and-rejection',
216
- });
217
229
  });
218
230
  }
219
231
  setupEventListeners() {
232
+ if (!this.canSetEventListeners)
233
+ return;
220
234
  const wallet = this.getWallet();
221
235
  if (!wallet) {
222
236
  return walletConnectorCore.logger.error('Wallet has not been found');
@@ -245,6 +259,8 @@ class StarknetWalletConnector extends walletConnectorCore.WalletConnectorBase {
245
259
  }
246
260
  teardownEventListeners() {
247
261
  return _tslib.__awaiter(this, void 0, void 0, function* () {
262
+ if (!this.canSetEventListeners)
263
+ return;
248
264
  const wallet = this.getWallet();
249
265
  if (this.handleAccountChange) {
250
266
  wallet === null || wallet === void 0 ? void 0 : wallet.off(ACCOUNT_CHANGED_EVENT_LISTENER, this.handleAccountChange);
@@ -3,7 +3,7 @@ import { ProviderInterface, constants, AccountInterface, RpcProvider } from 'sta
3
3
  import { Chain, WalletConnectorBase } from '@dynamic-labs/wallet-connector-core';
4
4
  import { NetworkConfiguration } from '@dynamic-labs/sdk-api-core';
5
5
  import { WalletBookSchema } from '@dynamic-labs/wallet-book';
6
- import { IChainRpcProviders } from '@dynamic-labs/rpc-provider-starknet';
6
+ import { IChainRpcProviders } from '@dynamic-labs/starknet-core';
7
7
  import { StarknetWalletKey } from './types';
8
8
  type AccountChangeEventHandler = (address: {
9
9
  toString(): string;
@@ -23,6 +23,7 @@ declare abstract class StarknetWalletConnector extends WalletConnectorBase {
23
23
  handleNetworkChange: NetworkChangeEventHandler | undefined;
24
24
  switchNetworkOnlyFromWallet: boolean;
25
25
  starknetNetworks: NetworkConfiguration[];
26
+ canSetEventListeners: boolean;
26
27
  constructor(name: string, windowKey: StarknetWalletKey, opts: {
27
28
  chainRpcProviders: IChainRpcProviders;
28
29
  starknetNetworks: NetworkConfiguration[];
@@ -63,6 +64,10 @@ declare abstract class StarknetWalletConnector extends WalletConnectorBase {
63
64
  features: string[];
64
65
  name: string;
65
66
  } | undefined;
67
+ walletStandardLocators?: {
68
+ name: string;
69
+ locator: string;
70
+ }[] | undefined;
66
71
  windowLocations?: string[] | undefined;
67
72
  }[] | undefined;
68
73
  mobile?: {
@@ -74,6 +79,7 @@ declare abstract class StarknetWalletConnector extends WalletConnectorBase {
74
79
  native?: string | undefined;
75
80
  universal?: string | undefined;
76
81
  } | undefined;
82
+ mobileExperience?: "in-app-browser" | "redirect" | undefined;
77
83
  shortName?: string | undefined;
78
84
  showOnlyIfInstalled?: boolean | undefined;
79
85
  switchNetworkOnlyFromWallet?: boolean | undefined;
@@ -81,6 +87,16 @@ declare abstract class StarknetWalletConnector extends WalletConnectorBase {
81
87
  sdks?: string[] | undefined;
82
88
  } | undefined;
83
89
  walletGroup?: string | undefined;
90
+ walletLimitations?: {
91
+ browserExtension?: {
92
+ unsupportedEvents?: string[] | undefined;
93
+ unsupportedMethods?: string[] | undefined;
94
+ } | undefined;
95
+ mobile?: {
96
+ unsupportedEvents?: string[] | undefined;
97
+ unsupportedMethods?: string[] | undefined;
98
+ } | undefined;
99
+ } | undefined;
84
100
  };
85
101
  isProviderConnected(): boolean;
86
102
  getPublicClient(): Promise<RpcProvider | undefined>;
@@ -93,11 +109,12 @@ declare abstract class StarknetWalletConnector extends WalletConnectorBase {
93
109
  getSigner(): Promise<AccountInterface | undefined>;
94
110
  getWalletClient(): Promise<ProviderInterface | undefined>;
95
111
  signMessage(messageToSign: string): Promise<string | undefined>;
96
- getBalance(): Promise<string | undefined>;
112
+ getBalance(address: string): Promise<string | undefined>;
97
113
  endSession(): Promise<void>;
98
114
  getWallet(): StarknetWindowObject | undefined;
99
115
  isInstalledOnBrowser(): boolean;
100
116
  getConnectedAccounts(): Promise<string[]>;
117
+ reconnectIfNeeded(wallet: StarknetWindowObject): Promise<Promise<Promise<void>>>;
101
118
  setupEventListeners(): void;
102
119
  teardownEventListeners(): Promise<void>;
103
120
  mapNetworkNameToChainId(networkNameOrChainId: string): constants.StarknetChainId | undefined;
@@ -18,6 +18,8 @@ class StarknetWalletConnector extends WalletConnectorBase {
18
18
  this.connectedChain = 'STARK';
19
19
  this.supportedChains = ['STARK'];
20
20
  this.switchNetworkOnlyFromWallet = true;
21
+ // required for metamask snap integration as MM snaps don't have event listeners
22
+ this.canSetEventListeners = true;
21
23
  this.name = name;
22
24
  this.windowKey = windowKey;
23
25
  this.starknetNetworks = opts.starknetNetworks;
@@ -87,7 +89,8 @@ class StarknetWalletConnector extends WalletConnectorBase {
87
89
  if (!this.isInstalledOnBrowser() &&
88
90
  isMobile() &&
89
91
  this.walletBookWallet.mobile &&
90
- this.walletBookWallet.mobile.inAppBrowser) {
92
+ this.walletBookWallet.mobile.inAppBrowser &&
93
+ this.mobileExperience === 'in-app-browser') {
91
94
  const inAppBrowserCompiledTemplate = template(this.walletBookWallet.mobile.inAppBrowser);
92
95
  const deepLink = inAppBrowserCompiledTemplate({
93
96
  encodedDappURI: encodeURIComponent(window.location.toString()),
@@ -127,17 +130,16 @@ class StarknetWalletConnector extends WalletConnectorBase {
127
130
  return signature === null || signature === void 0 ? void 0 : signature.join(',');
128
131
  });
129
132
  }
130
- getBalance() {
133
+ getBalance(address) {
131
134
  return __awaiter(this, void 0, void 0, function* () {
132
- const walletAddress = yield this.getAddress();
133
135
  const provider = yield this.getWalletClient();
134
- if (!walletAddress || !provider) {
135
- logger.error('Could not fetch wallet address for getting balance');
136
+ if (!provider) {
137
+ logger.error('Could not find provider for getting balance');
136
138
  return undefined;
137
139
  }
138
140
  const contract = new Contract(ETH_CONTRACT_ABI, ETH_STARKNET_ADDRESS, provider);
139
141
  try {
140
- const { balance } = yield contract.balanceOf(walletAddress);
142
+ const { balance } = yield contract.balanceOf(address);
141
143
  /**
142
144
  * Dividing by 1e18 as the returned balance is a Gwei number.
143
145
  * Read more here: https://www.investopedia.com/terms/g/gwei-ethereum.asp#toc-what-is-gwei
@@ -178,6 +180,24 @@ class StarknetWalletConnector extends WalletConnectorBase {
178
180
  if (!wallet) {
179
181
  return [];
180
182
  }
183
+ try {
184
+ yield this.reconnectIfNeeded(wallet);
185
+ }
186
+ catch (e) {
187
+ return [];
188
+ }
189
+ const getSelectedAddress = () => wallet.selectedAddress
190
+ ? Promise.resolve([wallet.selectedAddress])
191
+ : Promise.reject();
192
+ return retryableFn(getSelectedAddress, {
193
+ fallbackValue: [],
194
+ retryIntervalMs: 100,
195
+ retryStrategy: 'timeout-and-rejection',
196
+ });
197
+ });
198
+ }
199
+ reconnectIfNeeded(wallet) {
200
+ return __awaiter(this, void 0, void 0, function* () {
181
201
  const needsReconnection = !this.isProviderConnected() && (yield wallet.isPreauthorized());
182
202
  if (needsReconnection) {
183
203
  /**
@@ -195,24 +215,18 @@ class StarknetWalletConnector extends WalletConnectorBase {
195
215
  }
196
216
  catch (_a) {
197
217
  localStorage.removeItem('dynamic_should_have_wallet');
198
- return [];
218
+ throw new Error('Could not reconnect');
199
219
  }
200
220
  }
201
221
  else {
202
222
  yield this.connect();
203
223
  }
204
224
  }
205
- const getSelectedAddress = () => wallet.selectedAddress
206
- ? Promise.resolve([wallet.selectedAddress])
207
- : Promise.reject();
208
- return retryableFn(getSelectedAddress, {
209
- fallbackValue: [],
210
- retryIntervalMs: 100,
211
- retryStrategy: 'timeout-and-rejection',
212
- });
213
225
  });
214
226
  }
215
227
  setupEventListeners() {
228
+ if (!this.canSetEventListeners)
229
+ return;
216
230
  const wallet = this.getWallet();
217
231
  if (!wallet) {
218
232
  return logger.error('Wallet has not been found');
@@ -241,6 +255,8 @@ class StarknetWalletConnector extends WalletConnectorBase {
241
255
  }
242
256
  teardownEventListeners() {
243
257
  return __awaiter(this, void 0, void 0, function* () {
258
+ if (!this.canSetEventListeners)
259
+ return;
244
260
  const wallet = this.getWallet();
245
261
  if (this.handleAccountChange) {
246
262
  wallet === null || wallet === void 0 ? void 0 : wallet.off(ACCOUNT_CHANGED_EVENT_LISTENER, this.handleAccountChange);
package/src/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { StarknetWindowObject } from 'get-starknet-core';
2
- export type StarknetWalletKey = 'braavos' | 'argentX' | 'argentXMobile' | 'argentWebWallet' | 'okxwallet' | 'bitkeep';
2
+ export type StarknetWalletKey = 'braavos' | 'argentX' | 'argentXMobile' | 'argentWebWallet' | 'okxwallet' | 'bitkeep' | 'metamask_snap';
3
3
  export type StarknetWindowKey = `starknet_${StarknetWalletKey}` | 'starknet';
4
4
  type StarknetWindow = {
5
5
  [key in StarknetWindowKey]: StarknetWindowObject;
@@ -0,0 +1,92 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../_virtual/_tslib.cjs');
7
+ var index_cjs_js = require('@module-federation/runtime/dist/index.cjs.js');
8
+
9
+ /**
10
+ *
11
+ * @param {IEthereum} provider the metamask window provider object
12
+ * @returns {StarknetWindowObject} the metamask provider wrapper formed into starknet window object
13
+ */
14
+ const createMetaMaskProviderWrapper = (provider) => {
15
+ let metaMaskSnapWallet;
16
+ // using @module-federation to load the get-starknet remoteEntry, as recommended
17
+ // by the starknet team. this file is a small wrapper around the metamask snap api
18
+ // to communicate with starknet, which we then wrap into a starknet window object
19
+ // and use in our starknet connector, just like braavos and argent
20
+ const initMetaMaskSnapWallet = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
21
+ if (!metaMaskSnapWallet) {
22
+ index_cjs_js.init({
23
+ name: 'MetaMaskStarknetSnapWallet',
24
+ remotes: [
25
+ {
26
+ alias: 'MetaMaskStarknetSnapWallet',
27
+ entry: 'https://snaps.consensys.io/starknet/get-starknet/v1/remoteEntry.js',
28
+ name: 'MetaMaskStarknetSnapWallet',
29
+ },
30
+ ],
31
+ });
32
+ const result = yield index_cjs_js.loadRemote('MetaMaskStarknetSnapWallet/index');
33
+ const { MetaMaskSnapWallet } = result;
34
+ metaMaskSnapWallet = new MetaMaskSnapWallet(provider, '*');
35
+ }
36
+ });
37
+ const metaMaskProviderWrapper = {
38
+ get account() {
39
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.account;
40
+ },
41
+ get chainId() {
42
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.chainId;
43
+ },
44
+ enable: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
45
+ yield initMetaMaskSnapWallet();
46
+ if (!metaMaskSnapWallet) {
47
+ return [];
48
+ }
49
+ return metaMaskSnapWallet.enable();
50
+ }),
51
+ icon: '',
52
+ id: 'MetaMaskStarknetSnapWallet',
53
+ get isConnected() {
54
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.isConnected;
55
+ },
56
+ isPreauthorized: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
57
+ var _a;
58
+ yield initMetaMaskSnapWallet();
59
+ return (_a = (yield (metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.isPreauthorized()))) !== null && _a !== void 0 ? _a : false;
60
+ }),
61
+ name: 'MetaMaskStarknetSnapWallet',
62
+ off: (
63
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
64
+ event,
65
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
66
+ handleEvent) => undefined,
67
+ on: (
68
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
69
+ event,
70
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
71
+ handleEvent) => undefined,
72
+ get provider() {
73
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.provider;
74
+ },
75
+ request: (call) => {
76
+ if (!metaMaskSnapWallet) {
77
+ throw new Error('Wallet not enabled');
78
+ }
79
+ return metaMaskSnapWallet.request(call);
80
+ },
81
+ get selectedAddress() {
82
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.selectedAddress;
83
+ },
84
+ get version() {
85
+ var _a;
86
+ return (_a = metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.version) !== null && _a !== void 0 ? _a : '0.0.0';
87
+ },
88
+ };
89
+ return metaMaskProviderWrapper;
90
+ };
91
+
92
+ exports.createMetaMaskProviderWrapper = createMetaMaskProviderWrapper;
@@ -0,0 +1,8 @@
1
+ import { StarknetWindowObject } from 'get-starknet-core';
2
+ import { IEthereum } from '@dynamic-labs/utils';
3
+ /**
4
+ *
5
+ * @param {IEthereum} provider the metamask window provider object
6
+ * @returns {StarknetWindowObject} the metamask provider wrapper formed into starknet window object
7
+ */
8
+ export declare const createMetaMaskProviderWrapper: (provider: IEthereum) => StarknetWindowObject;
@@ -0,0 +1,88 @@
1
+ 'use client'
2
+ import { __awaiter } from '../../_virtual/_tslib.js';
3
+ import { init, loadRemote } from '@module-federation/runtime/dist/index.cjs.js';
4
+
5
+ /**
6
+ *
7
+ * @param {IEthereum} provider the metamask window provider object
8
+ * @returns {StarknetWindowObject} the metamask provider wrapper formed into starknet window object
9
+ */
10
+ const createMetaMaskProviderWrapper = (provider) => {
11
+ let metaMaskSnapWallet;
12
+ // using @module-federation to load the get-starknet remoteEntry, as recommended
13
+ // by the starknet team. this file is a small wrapper around the metamask snap api
14
+ // to communicate with starknet, which we then wrap into a starknet window object
15
+ // and use in our starknet connector, just like braavos and argent
16
+ const initMetaMaskSnapWallet = () => __awaiter(void 0, void 0, void 0, function* () {
17
+ if (!metaMaskSnapWallet) {
18
+ init({
19
+ name: 'MetaMaskStarknetSnapWallet',
20
+ remotes: [
21
+ {
22
+ alias: 'MetaMaskStarknetSnapWallet',
23
+ entry: 'https://snaps.consensys.io/starknet/get-starknet/v1/remoteEntry.js',
24
+ name: 'MetaMaskStarknetSnapWallet',
25
+ },
26
+ ],
27
+ });
28
+ const result = yield loadRemote('MetaMaskStarknetSnapWallet/index');
29
+ const { MetaMaskSnapWallet } = result;
30
+ metaMaskSnapWallet = new MetaMaskSnapWallet(provider, '*');
31
+ }
32
+ });
33
+ const metaMaskProviderWrapper = {
34
+ get account() {
35
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.account;
36
+ },
37
+ get chainId() {
38
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.chainId;
39
+ },
40
+ enable: () => __awaiter(void 0, void 0, void 0, function* () {
41
+ yield initMetaMaskSnapWallet();
42
+ if (!metaMaskSnapWallet) {
43
+ return [];
44
+ }
45
+ return metaMaskSnapWallet.enable();
46
+ }),
47
+ icon: '',
48
+ id: 'MetaMaskStarknetSnapWallet',
49
+ get isConnected() {
50
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.isConnected;
51
+ },
52
+ isPreauthorized: () => __awaiter(void 0, void 0, void 0, function* () {
53
+ var _a;
54
+ yield initMetaMaskSnapWallet();
55
+ return (_a = (yield (metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.isPreauthorized()))) !== null && _a !== void 0 ? _a : false;
56
+ }),
57
+ name: 'MetaMaskStarknetSnapWallet',
58
+ off: (
59
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
60
+ event,
61
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
62
+ handleEvent) => undefined,
63
+ on: (
64
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
65
+ event,
66
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
67
+ handleEvent) => undefined,
68
+ get provider() {
69
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.provider;
70
+ },
71
+ request: (call) => {
72
+ if (!metaMaskSnapWallet) {
73
+ throw new Error('Wallet not enabled');
74
+ }
75
+ return metaMaskSnapWallet.request(call);
76
+ },
77
+ get selectedAddress() {
78
+ return metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.selectedAddress;
79
+ },
80
+ get version() {
81
+ var _a;
82
+ return (_a = metaMaskSnapWallet === null || metaMaskSnapWallet === void 0 ? void 0 : metaMaskSnapWallet.version) !== null && _a !== void 0 ? _a : '0.0.0';
83
+ },
84
+ };
85
+ return metaMaskProviderWrapper;
86
+ };
87
+
88
+ export { createMetaMaskProviderWrapper };
@@ -0,0 +1,121 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../_virtual/_tslib.cjs');
7
+ var utils = require('@dynamic-labs/utils');
8
+ var logger$1 = require('@dynamic-labs/logger');
9
+ var starknetWalletConnector = require('../starknetWalletConnector.cjs');
10
+ var starknetSnap = require('../utils/starknetSnap.cjs');
11
+
12
+ const logger = new logger$1.Logger('MetaMask Starknet Snap', logger$1.LogLevel.INFO);
13
+ class MetaMask extends starknetWalletConnector["default"] {
14
+ constructor(opts) {
15
+ super('MetaMask Starknet', 'metamask_snap', opts);
16
+ this.overrideKey = 'metamaskstarknet';
17
+ const { providers } = utils.Eip6963ProviderSingleton.get();
18
+ const metamaskProvider = providers.find((p) => ['io.metamask', 'io.metamask.flask'].includes(p.info.rdns));
19
+ if (metamaskProvider) {
20
+ this.provider = metamaskProvider.provider;
21
+ }
22
+ if (!window.starknet_metamask_snap && metamaskProvider) {
23
+ window.starknet_metamask_snap = starknetSnap.createMetaMaskProviderWrapper(metamaskProvider.provider);
24
+ }
25
+ }
26
+ getNetwork() {
27
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
28
+ if (!this.provider) {
29
+ logger.error('[getNetwork] - No provider found, returning undefined');
30
+ return undefined;
31
+ }
32
+ try {
33
+ logger.info('[getNetwork] - trying to fetch network using provider');
34
+ // we are using this method to get the network so that we always "see" the absolute
35
+ // active network in the companion site. when using the snap wrapper to get the network,
36
+ // we don't "see" the actual active network in the companion site – instead we see the
37
+ // network that was active at the time of the snap initialization
38
+ const result = yield this.provider.request({
39
+ method: 'wallet_invokeSnap',
40
+ params: {
41
+ request: {
42
+ method: 'starkNet_getCurrentNetwork',
43
+ params: {},
44
+ },
45
+ snapId: 'npm:@consensys/starknet-snap',
46
+ },
47
+ });
48
+ if (!('chainId' in result) || typeof result.chainId !== 'string') {
49
+ logger.error(`[getNetwork] - result.chainId should be a string, but got: ${
50
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
+ result.chainId}`);
52
+ return undefined;
53
+ }
54
+ if (result.chainId !== this.currentChainId) {
55
+ const resultChainName = this.mapChainIdToNetworkName(result.chainId);
56
+ const currentChainName = this.currentChainId
57
+ ? this.mapChainIdToNetworkName(this.currentChainId)
58
+ : undefined;
59
+ logger.info(`[getNetwork] - emitting chainChange event. got chainId: ${result.chainId} (${resultChainName}). current chainId: ${this.currentChainId} (${currentChainName})`);
60
+ this.emit('chainChange', { chain: result.chainId });
61
+ }
62
+ this.currentChainId = result.chainId;
63
+ return this.currentChainId;
64
+ }
65
+ catch (e) {
66
+ logger.error('[getNetwork] - network fetch request failed, returning undefined', e);
67
+ return undefined;
68
+ }
69
+ });
70
+ }
71
+ setupEventListeners() {
72
+ if (this.intervalId) {
73
+ return;
74
+ }
75
+ this.intervalId = setInterval(() => {
76
+ this.getNetwork().then((chainId) => {
77
+ if (!chainId) {
78
+ return;
79
+ }
80
+ const resultChainName = this.mapChainIdToNetworkName(chainId);
81
+ const currentChainName = this.currentChainId
82
+ ? this.mapChainIdToNetworkName(this.currentChainId)
83
+ : undefined;
84
+ logger.info(`[setupEventListeners] - got network: ${chainId} (${resultChainName}). current network: ${this.currentChainId} (${currentChainName})`);
85
+ if (chainId !== this.currentChainId) {
86
+ logger.info(`[setupEventListeners] - emitting chainChange event: ${chainId}`);
87
+ this.emit('chainChange', { chain: chainId });
88
+ this.currentChainId = chainId;
89
+ }
90
+ });
91
+ }, 5000);
92
+ }
93
+ teardownEventListeners() {
94
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
95
+ clearInterval(this.intervalId);
96
+ this.intervalId = undefined;
97
+ });
98
+ }
99
+ endSession() {
100
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
101
+ this.teardownEventListeners();
102
+ });
103
+ }
104
+ getConnectedAccounts() {
105
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
106
+ const wallet = this.getWallet();
107
+ if (!wallet) {
108
+ return [];
109
+ }
110
+ const isProviderConnected = this.isProviderConnected();
111
+ const isPreauthorized = yield wallet.isPreauthorized();
112
+ const shouldReconnect = !isProviderConnected && isPreauthorized;
113
+ if (shouldReconnect) {
114
+ yield this.connect();
115
+ }
116
+ return wallet.selectedAddress ? [wallet.selectedAddress] : [];
117
+ });
118
+ }
119
+ }
120
+
121
+ exports.MetaMask = MetaMask;
@@ -0,0 +1,14 @@
1
+ import { type WalletConnector } from '@dynamic-labs/wallet-connector-core';
2
+ import StarknetProvider from '../starknetWalletConnector';
3
+ export declare class MetaMask extends StarknetProvider implements WalletConnector {
4
+ overrideKey: string;
5
+ private currentChainId;
6
+ private intervalId;
7
+ private provider;
8
+ constructor(opts: any);
9
+ getNetwork(): Promise<string | undefined>;
10
+ setupEventListeners(): void;
11
+ teardownEventListeners(): Promise<void>;
12
+ endSession(): Promise<void>;
13
+ getConnectedAccounts(): Promise<string[]>;
14
+ }