@dynamic-labs/starknet 3.0.0-alpha.9 → 3.0.0

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.
@@ -5,21 +5,101 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
 
6
6
  var _tslib = require('../../_virtual/_tslib.cjs');
7
7
  var utils = require('@dynamic-labs/utils');
8
+ var logger$1 = require('@dynamic-labs/logger');
8
9
  var starknetWalletConnector = require('../starknetWalletConnector.cjs');
9
10
  var starknetSnap = require('../utils/starknetSnap.cjs');
10
11
 
12
+ const logger = new logger$1.Logger('MetaMask Starknet Snap', logger$1.LogLevel.INFO);
11
13
  class MetaMask extends starknetWalletConnector["default"] {
12
14
  constructor(opts) {
13
15
  super('MetaMask Starknet', 'metamask_snap', opts);
14
16
  this.overrideKey = 'metamaskstarknet';
15
- this.canSetEventListeners = false;
16
- if (!window.starknet_metamask_snap) {
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
- window.starknet_metamask_snap = starknetSnap.createMetaMaskProviderWrapper(metamaskProvider.provider);
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;
21
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;
22
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
+ });
23
103
  }
24
104
  getConnectedAccounts() {
25
105
  return _tslib.__awaiter(this, void 0, void 0, function* () {
@@ -27,21 +107,13 @@ class MetaMask extends starknetWalletConnector["default"] {
27
107
  if (!wallet) {
28
108
  return [];
29
109
  }
30
- try {
31
- yield this.reconnectIfNeeded(wallet);
110
+ const isProviderConnected = this.isProviderConnected();
111
+ const isPreauthorized = yield wallet.isPreauthorized();
112
+ const shouldReconnect = !isProviderConnected && isPreauthorized;
113
+ if (shouldReconnect) {
114
+ yield this.connect();
32
115
  }
33
- catch (e) {
34
- return [];
35
- }
36
- const getSelectedAddress = () => wallet.selectedAddress
37
- ? Promise.resolve([wallet.selectedAddress])
38
- : Promise.reject();
39
- return utils.retryableFn(getSelectedAddress, {
40
- fallbackValue: [],
41
- maxRetries: 10,
42
- retryIntervalMs: 750,
43
- retryStrategy: 'timeout-and-rejection',
44
- });
116
+ return wallet.selectedAddress ? [wallet.selectedAddress] : [];
45
117
  });
46
118
  }
47
119
  }
@@ -1,8 +1,14 @@
1
- import { type WalletConnector } from '@dynamic-labs/wallet-connector-core';
1
+ import { WalletConnectorBase } from '@dynamic-labs/wallet-connector-core';
2
2
  import StarknetProvider from '../starknetWalletConnector';
3
- export declare class MetaMask extends StarknetProvider implements WalletConnector {
3
+ export declare class MetaMask extends StarknetProvider implements WalletConnectorBase {
4
4
  overrideKey: string;
5
- canSetEventListeners: boolean;
5
+ private currentChainId;
6
+ private intervalId;
7
+ private provider;
6
8
  constructor(opts: any);
9
+ getNetwork(): Promise<string | undefined>;
10
+ setupEventListeners(): void;
11
+ teardownEventListeners(): Promise<void>;
12
+ endSession(): Promise<void>;
7
13
  getConnectedAccounts(): Promise<string[]>;
8
14
  }
@@ -1,21 +1,101 @@
1
1
  'use client'
2
2
  import { __awaiter } from '../../_virtual/_tslib.js';
3
- import { Eip6963ProviderSingleton, retryableFn } from '@dynamic-labs/utils';
3
+ import { Eip6963ProviderSingleton } from '@dynamic-labs/utils';
4
+ import { Logger, LogLevel } from '@dynamic-labs/logger';
4
5
  import StarknetWalletConnector from '../starknetWalletConnector.js';
5
6
  import { createMetaMaskProviderWrapper } from '../utils/starknetSnap.js';
6
7
 
8
+ const logger = new Logger('MetaMask Starknet Snap', LogLevel.INFO);
7
9
  class MetaMask extends StarknetWalletConnector {
8
10
  constructor(opts) {
9
11
  super('MetaMask Starknet', 'metamask_snap', opts);
10
12
  this.overrideKey = 'metamaskstarknet';
11
- this.canSetEventListeners = false;
12
- if (!window.starknet_metamask_snap) {
13
- const { providers } = Eip6963ProviderSingleton.get();
14
- const metamaskProvider = providers.find((p) => ['io.metamask', 'io.metamask.flask'].includes(p.info.rdns));
15
- if (metamaskProvider) {
16
- window.starknet_metamask_snap = createMetaMaskProviderWrapper(metamaskProvider.provider);
13
+ const { providers } = Eip6963ProviderSingleton.get();
14
+ const metamaskProvider = providers.find((p) => ['io.metamask', 'io.metamask.flask'].includes(p.info.rdns));
15
+ if (metamaskProvider) {
16
+ this.provider = metamaskProvider.provider;
17
+ }
18
+ if (!window.starknet_metamask_snap && metamaskProvider) {
19
+ window.starknet_metamask_snap = createMetaMaskProviderWrapper(metamaskProvider.provider);
20
+ }
21
+ }
22
+ getNetwork() {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ if (!this.provider) {
25
+ logger.error('[getNetwork] - No provider found, returning undefined');
26
+ return undefined;
27
+ }
28
+ try {
29
+ logger.info('[getNetwork] - trying to fetch network using provider');
30
+ // we are using this method to get the network so that we always "see" the absolute
31
+ // active network in the companion site. when using the snap wrapper to get the network,
32
+ // we don't "see" the actual active network in the companion site – instead we see the
33
+ // network that was active at the time of the snap initialization
34
+ const result = yield this.provider.request({
35
+ method: 'wallet_invokeSnap',
36
+ params: {
37
+ request: {
38
+ method: 'starkNet_getCurrentNetwork',
39
+ params: {},
40
+ },
41
+ snapId: 'npm:@consensys/starknet-snap',
42
+ },
43
+ });
44
+ if (!('chainId' in result) || typeof result.chainId !== 'string') {
45
+ logger.error(`[getNetwork] - result.chainId should be a string, but got: ${
46
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
+ result.chainId}`);
48
+ return undefined;
49
+ }
50
+ if (result.chainId !== this.currentChainId) {
51
+ const resultChainName = this.mapChainIdToNetworkName(result.chainId);
52
+ const currentChainName = this.currentChainId
53
+ ? this.mapChainIdToNetworkName(this.currentChainId)
54
+ : undefined;
55
+ logger.info(`[getNetwork] - emitting chainChange event. got chainId: ${result.chainId} (${resultChainName}). current chainId: ${this.currentChainId} (${currentChainName})`);
56
+ this.emit('chainChange', { chain: result.chainId });
57
+ }
58
+ this.currentChainId = result.chainId;
59
+ return this.currentChainId;
17
60
  }
61
+ catch (e) {
62
+ logger.error('[getNetwork] - network fetch request failed, returning undefined', e);
63
+ return undefined;
64
+ }
65
+ });
66
+ }
67
+ setupEventListeners() {
68
+ if (this.intervalId) {
69
+ return;
18
70
  }
71
+ this.intervalId = setInterval(() => {
72
+ this.getNetwork().then((chainId) => {
73
+ if (!chainId) {
74
+ return;
75
+ }
76
+ const resultChainName = this.mapChainIdToNetworkName(chainId);
77
+ const currentChainName = this.currentChainId
78
+ ? this.mapChainIdToNetworkName(this.currentChainId)
79
+ : undefined;
80
+ logger.info(`[setupEventListeners] - got network: ${chainId} (${resultChainName}). current network: ${this.currentChainId} (${currentChainName})`);
81
+ if (chainId !== this.currentChainId) {
82
+ logger.info(`[setupEventListeners] - emitting chainChange event: ${chainId}`);
83
+ this.emit('chainChange', { chain: chainId });
84
+ this.currentChainId = chainId;
85
+ }
86
+ });
87
+ }, 5000);
88
+ }
89
+ teardownEventListeners() {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ clearInterval(this.intervalId);
92
+ this.intervalId = undefined;
93
+ });
94
+ }
95
+ endSession() {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ this.teardownEventListeners();
98
+ });
19
99
  }
20
100
  getConnectedAccounts() {
21
101
  return __awaiter(this, void 0, void 0, function* () {
@@ -23,21 +103,13 @@ class MetaMask extends StarknetWalletConnector {
23
103
  if (!wallet) {
24
104
  return [];
25
105
  }
26
- try {
27
- yield this.reconnectIfNeeded(wallet);
106
+ const isProviderConnected = this.isProviderConnected();
107
+ const isPreauthorized = yield wallet.isPreauthorized();
108
+ const shouldReconnect = !isProviderConnected && isPreauthorized;
109
+ if (shouldReconnect) {
110
+ yield this.connect();
28
111
  }
29
- catch (e) {
30
- return [];
31
- }
32
- const getSelectedAddress = () => wallet.selectedAddress
33
- ? Promise.resolve([wallet.selectedAddress])
34
- : Promise.reject();
35
- return retryableFn(getSelectedAddress, {
36
- fallbackValue: [],
37
- maxRetries: 10,
38
- retryIntervalMs: 750,
39
- retryStrategy: 'timeout-and-rejection',
40
- });
112
+ return wallet.selectedAddress ? [wallet.selectedAddress] : [];
41
113
  });
42
114
  }
43
115
  }
@@ -1,6 +1,6 @@
1
- import type { WalletConnector } from '@dynamic-labs/wallet-connector-core';
1
+ import type { WalletConnectorBase } from '@dynamic-labs/wallet-connector-core';
2
2
  import StarknetProvider from '../starknetWalletConnector';
3
- export declare class Okx extends StarknetProvider implements WalletConnector {
3
+ export declare class Okx extends StarknetProvider implements WalletConnectorBase {
4
4
  overrideKey: string;
5
5
  constructor(opts: any);
6
6
  }