@dynamic-labs/ethereum 0.19.0-alpha.2 → 0.19.0-alpha.21

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.
Files changed (118) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/package.json +13 -10
  3. package/src/EthWalletConnector.cjs +189 -193
  4. package/src/EthWalletConnector.d.ts +298 -41
  5. package/src/EthWalletConnector.js +190 -194
  6. package/src/coinbase/client/client.cjs +76 -0
  7. package/src/coinbase/client/client.d.ts +6 -0
  8. package/src/coinbase/client/client.js +69 -0
  9. package/src/coinbase/client/index.d.ts +2 -0
  10. package/src/coinbase/client/types.d.ts +14 -0
  11. package/src/coinbase/coinbase.cjs +71 -0
  12. package/src/coinbase/coinbase.d.ts +535 -0
  13. package/src/coinbase/coinbase.js +67 -0
  14. package/src/coinbase/index.d.ts +3 -0
  15. package/src/constants.d.ts +1 -1
  16. package/src/ethProviderHelper.cjs +132 -209
  17. package/src/ethProviderHelper.d.ts +28 -36
  18. package/src/ethProviderHelper.js +133 -210
  19. package/src/index.cjs +30 -26
  20. package/src/index.d.ts +9 -8
  21. package/src/index.js +25 -20
  22. package/src/injected/BloctoInjected.cjs +6 -6
  23. package/src/injected/BloctoInjected.d.ts +4 -4
  24. package/src/injected/BloctoInjected.js +6 -6
  25. package/src/injected/BraveEvm.cjs +6 -6
  26. package/src/injected/BraveEvm.d.ts +4 -4
  27. package/src/injected/BraveEvm.js +6 -6
  28. package/src/injected/Dawn.cjs +6 -6
  29. package/src/injected/Dawn.d.ts +4 -4
  30. package/src/injected/Dawn.js +6 -6
  31. package/src/injected/ExodusEvm.cjs +8 -8
  32. package/src/injected/ExodusEvm.d.ts +5 -5
  33. package/src/injected/ExodusEvm.js +7 -7
  34. package/src/injected/Frame.cjs +6 -6
  35. package/src/injected/Frame.d.ts +4 -4
  36. package/src/injected/Frame.js +6 -6
  37. package/src/injected/GameStop.cjs +6 -6
  38. package/src/injected/GameStop.d.ts +4 -4
  39. package/src/injected/GameStop.js +6 -6
  40. package/src/injected/InjectedWalletBase.cjs +86 -65
  41. package/src/injected/InjectedWalletBase.d.ts +29 -24
  42. package/src/injected/InjectedWalletBase.js +86 -65
  43. package/src/injected/LegacyInjectedWalletBase.cjs +83 -0
  44. package/src/injected/LegacyInjectedWalletBase.d.ts +24 -0
  45. package/src/injected/LegacyInjectedWalletBase.js +81 -0
  46. package/src/injected/Opera.cjs +6 -6
  47. package/src/injected/Opera.d.ts +4 -4
  48. package/src/injected/Opera.js +6 -6
  49. package/src/injected/PhantomEvm.cjs +28 -28
  50. package/src/injected/PhantomEvm.d.ts +5 -5
  51. package/src/injected/PhantomEvm.js +28 -28
  52. package/src/injected/Rabby.cjs +8 -8
  53. package/src/injected/Rabby.d.ts +5 -5
  54. package/src/injected/Rabby.js +7 -7
  55. package/src/injected/Superb.cjs +6 -6
  56. package/src/injected/Superb.d.ts +4 -4
  57. package/src/injected/Superb.js +6 -6
  58. package/src/injected/Trust.cjs +8 -8
  59. package/src/injected/Trust.d.ts +5 -5
  60. package/src/injected/Trust.js +7 -7
  61. package/src/injected/Zerion.cjs +8 -8
  62. package/src/injected/Zerion.d.ts +5 -5
  63. package/src/injected/Zerion.js +7 -7
  64. package/src/injected/fetchInjectedWalletConnectors.cjs +33 -0
  65. package/src/injected/fetchInjectedWalletConnectors.d.ts +6 -0
  66. package/src/injected/fetchInjectedWalletConnectors.js +29 -0
  67. package/src/injected/index.d.ts +13 -16
  68. package/src/injected/legacyInjectedWallets.cjs +48 -0
  69. package/src/injected/legacyInjectedWallets.d.ts +3 -0
  70. package/src/injected/legacyInjectedWallets.js +43 -0
  71. package/src/legacyEthProviderHelper.cjs +187 -0
  72. package/src/legacyEthProviderHelper.d.ts +34 -0
  73. package/src/legacyEthProviderHelper.js +183 -0
  74. package/src/polyfills.cjs +11 -11
  75. package/src/polyfills.d.ts +1 -1
  76. package/src/polyfills.js +11 -11
  77. package/src/types.d.ts +37 -24
  78. package/src/utils/eventListenerHandlers.cjs +34 -0
  79. package/src/utils/eventListenerHandlers.d.ts +8 -0
  80. package/src/utils/eventListenerHandlers.js +30 -0
  81. package/src/utils/findEvmNetwork.cjs +13 -13
  82. package/src/utils/findEvmNetwork.d.ts +6 -6
  83. package/src/utils/findEvmNetwork.js +13 -13
  84. package/src/utils/isString.d.ts +1 -1
  85. package/src/utils/isUnsupportedProviderError/index.d.ts +1 -1
  86. package/src/utils/isUnsupportedProviderError/isUnsupportedProviderError.cjs +6 -6
  87. package/src/utils/isUnsupportedProviderError/isUnsupportedProviderError.d.ts +6 -6
  88. package/src/utils/isUnsupportedProviderError/isUnsupportedProviderError.js +6 -6
  89. package/src/utils/last.d.ts +1 -1
  90. package/src/utils/parseIntSafe.cjs +13 -13
  91. package/src/utils/parseIntSafe.d.ts +1 -1
  92. package/src/utils/parseIntSafe.js +13 -13
  93. package/src/walletConnect/client/client.cjs +179 -176
  94. package/src/walletConnect/client/client.d.ts +17 -17
  95. package/src/walletConnect/client/client.js +179 -176
  96. package/src/walletConnect/client/index.d.ts +1 -1
  97. package/src/walletConnect/client/types.d.ts +4 -4
  98. package/src/walletConnect/fetchWalletConnectWallets.cjs +37 -52
  99. package/src/walletConnect/fetchWalletConnectWallets.d.ts +9 -10
  100. package/src/walletConnect/fetchWalletConnectWallets.js +38 -52
  101. package/src/walletConnect/index.d.ts +3 -3
  102. package/src/walletConnect/walletConnect.cjs +131 -130
  103. package/src/walletConnect/walletConnect.d.ts +52 -50
  104. package/src/walletConnect/walletConnect.js +131 -130
  105. package/src/walletConnect/walletConnectV2.cjs +419 -374
  106. package/src/walletConnect/walletConnectV2.d.ts +326 -61
  107. package/src/walletConnect/walletConnectV2.js +420 -375
  108. package/src/injected/MetaMask.cjs +0 -15
  109. package/src/injected/MetaMask.d.ts +0 -5
  110. package/src/injected/MetaMask.js +0 -11
  111. package/src/injected/OKX.cjs +0 -15
  112. package/src/injected/OKX.d.ts +0 -5
  113. package/src/injected/OKX.js +0 -11
  114. package/src/injected/UnknownInjectedWallet.cjs +0 -14
  115. package/src/injected/UnknownInjectedWallet.d.ts +0 -4
  116. package/src/injected/UnknownInjectedWallet.js +0 -10
  117. package/src/injected/index.cjs +0 -53
  118. package/src/injected/index.js +0 -49
@@ -0,0 +1,30 @@
1
+ import { __awaiter } from '../../_virtual/_tslib.js';
2
+
3
+ const eventListenerHandlers = (walletConnector, publicClient) => {
4
+ const handleAccountChange = (accounts) => __awaiter(void 0, void 0, void 0, function* () {
5
+ if (accounts.length === 0) {
6
+ walletConnector.emit('disconnect');
7
+ return;
8
+ }
9
+ walletConnector.emit('accountChange', { accounts });
10
+ });
11
+ const handleChainChange = () => __awaiter(void 0, void 0, void 0, function* () {
12
+ const chainId = yield publicClient.getChainId();
13
+ walletConnector.emit('chainChange', {
14
+ chain: chainId.toString(),
15
+ });
16
+ });
17
+ const handleDisconnect = (error) => __awaiter(void 0, void 0, void 0, function* () {
18
+ if ((error === null || error === void 0 ? void 0 : error.code) === 1013) {
19
+ return;
20
+ }
21
+ walletConnector.emit('disconnect');
22
+ });
23
+ return {
24
+ handleAccountChange,
25
+ handleChainChange,
26
+ handleDisconnect,
27
+ };
28
+ };
29
+
30
+ export { eventListenerHandlers };
@@ -2,19 +2,19 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- const findEvmNetwork = ({ chainId, name, networks, }) => {
6
- if (!chainId && !name) {
7
- return undefined;
8
- }
9
- if (chainId && name) {
10
- return networks.find((network) => network.chainId === chainId && network.name === name);
11
- }
12
- else if (chainId) {
13
- return networks.find((network) => network.chainId === chainId);
14
- }
15
- else {
16
- return networks.find((network) => network.name === name);
17
- }
5
+ const findEvmNetwork = ({ chainId, name, networks, }) => {
6
+ if (!chainId && !name) {
7
+ return undefined;
8
+ }
9
+ if (chainId && name) {
10
+ return networks.find((network) => network.chainId === chainId && network.name === name);
11
+ }
12
+ else if (chainId) {
13
+ return networks.find((network) => network.chainId === chainId);
14
+ }
15
+ else {
16
+ return networks.find((network) => network.name === name);
17
+ }
18
18
  };
19
19
 
20
20
  exports.findEvmNetwork = findEvmNetwork;
@@ -1,6 +1,6 @@
1
- import { EvmNetwork } from '@dynamic-labs/types';
2
- export declare const findEvmNetwork: ({ chainId, name, networks, }: {
3
- chainId?: number | undefined;
4
- name?: string | undefined;
5
- networks: EvmNetwork[];
6
- }) => EvmNetwork | undefined;
1
+ import { EvmNetwork } from '@dynamic-labs/types';
2
+ export declare const findEvmNetwork: ({ chainId, name, networks, }: {
3
+ chainId?: number | undefined;
4
+ name?: string | undefined;
5
+ networks: EvmNetwork[];
6
+ }) => EvmNetwork | undefined;
@@ -1,16 +1,16 @@
1
- const findEvmNetwork = ({ chainId, name, networks, }) => {
2
- if (!chainId && !name) {
3
- return undefined;
4
- }
5
- if (chainId && name) {
6
- return networks.find((network) => network.chainId === chainId && network.name === name);
7
- }
8
- else if (chainId) {
9
- return networks.find((network) => network.chainId === chainId);
10
- }
11
- else {
12
- return networks.find((network) => network.name === name);
13
- }
1
+ const findEvmNetwork = ({ chainId, name, networks, }) => {
2
+ if (!chainId && !name) {
3
+ return undefined;
4
+ }
5
+ if (chainId && name) {
6
+ return networks.find((network) => network.chainId === chainId && network.name === name);
7
+ }
8
+ else if (chainId) {
9
+ return networks.find((network) => network.chainId === chainId);
10
+ }
11
+ else {
12
+ return networks.find((network) => network.name === name);
13
+ }
14
14
  };
15
15
 
16
16
  export { findEvmNetwork };
@@ -1 +1 @@
1
- export declare const isString: (value: unknown) => value is string;
1
+ export declare const isString: (value: unknown) => value is string;
@@ -1 +1 @@
1
- export { isUnsupportedProviderError } from './isUnsupportedProviderError';
1
+ export { isUnsupportedProviderError } from './isUnsupportedProviderError';
@@ -2,12 +2,12 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- const isUnsupportedProviderError = (error) => {
6
- const isObject = typeof error === 'object';
7
- if (!isObject)
8
- return false;
9
- const isUnsupportedProviderErrorReason = error['reason'] === 'unsupported provider';
10
- return isUnsupportedProviderErrorReason;
5
+ const isUnsupportedProviderError = (error) => {
6
+ const isObject = typeof error === 'object';
7
+ if (!isObject)
8
+ return false;
9
+ const isUnsupportedProviderErrorReason = error['reason'] === 'unsupported provider';
10
+ return isUnsupportedProviderErrorReason;
11
11
  };
12
12
 
13
13
  exports.isUnsupportedProviderError = isUnsupportedProviderError;
@@ -1,6 +1,6 @@
1
- type UnsupportedProviderError = {
2
- reason: string;
3
- value: unknown;
4
- };
5
- export declare const isUnsupportedProviderError: (error: UnsupportedProviderError | unknown) => error is UnsupportedProviderError;
6
- export {};
1
+ type UnsupportedProviderError = {
2
+ reason: string;
3
+ value: unknown;
4
+ };
5
+ export declare const isUnsupportedProviderError: (error: UnsupportedProviderError | unknown) => error is UnsupportedProviderError;
6
+ export {};
@@ -1,9 +1,9 @@
1
- const isUnsupportedProviderError = (error) => {
2
- const isObject = typeof error === 'object';
3
- if (!isObject)
4
- return false;
5
- const isUnsupportedProviderErrorReason = error['reason'] === 'unsupported provider';
6
- return isUnsupportedProviderErrorReason;
1
+ const isUnsupportedProviderError = (error) => {
2
+ const isObject = typeof error === 'object';
3
+ if (!isObject)
4
+ return false;
5
+ const isUnsupportedProviderErrorReason = error['reason'] === 'unsupported provider';
6
+ return isUnsupportedProviderErrorReason;
7
7
  };
8
8
 
9
9
  export { isUnsupportedProviderError };
@@ -1 +1 @@
1
- export declare const last: <T = unknown>(array: T[]) => T | undefined;
1
+ export declare const last: <T = unknown>(array: T[]) => T | undefined;
@@ -4,19 +4,19 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
6
6
 
7
- const parseIntSafe = (value, radix = 10) => {
8
- try {
9
- const int = parseInt(String(value), radix);
10
- if (isNaN(int)) {
11
- walletConnectorCore.logger.error(`Error parsing ${value}`);
12
- return undefined;
13
- }
14
- return int;
15
- }
16
- catch (e) {
17
- walletConnectorCore.logger.error(`Error parsing ${value} to int: ${e}`);
18
- }
19
- return undefined;
7
+ const parseIntSafe = (value, radix = 10) => {
8
+ try {
9
+ const int = parseInt(String(value), radix);
10
+ if (isNaN(int)) {
11
+ walletConnectorCore.logger.error(`Error parsing ${value}`);
12
+ return undefined;
13
+ }
14
+ return int;
15
+ }
16
+ catch (e) {
17
+ walletConnectorCore.logger.error(`Error parsing ${value} to int: ${e}`);
18
+ }
19
+ return undefined;
20
20
  };
21
21
 
22
22
  exports.parseIntSafe = parseIntSafe;
@@ -1 +1 @@
1
- export declare const parseIntSafe: (value: string | number, radix?: number) => number | undefined;
1
+ export declare const parseIntSafe: (value: string | number, radix?: number) => number | undefined;
@@ -1,18 +1,18 @@
1
1
  import { logger } from '@dynamic-labs/wallet-connector-core';
2
2
 
3
- const parseIntSafe = (value, radix = 10) => {
4
- try {
5
- const int = parseInt(String(value), radix);
6
- if (isNaN(int)) {
7
- logger.error(`Error parsing ${value}`);
8
- return undefined;
9
- }
10
- return int;
11
- }
12
- catch (e) {
13
- logger.error(`Error parsing ${value} to int: ${e}`);
14
- }
15
- return undefined;
3
+ const parseIntSafe = (value, radix = 10) => {
4
+ try {
5
+ const int = parseInt(String(value), radix);
6
+ if (isNaN(int)) {
7
+ logger.error(`Error parsing ${value}`);
8
+ return undefined;
9
+ }
10
+ return int;
11
+ }
12
+ catch (e) {
13
+ logger.error(`Error parsing ${value} to int: ${e}`);
14
+ }
15
+ return undefined;
16
16
  };
17
17
 
18
18
  export { parseIntSafe };
@@ -4,7 +4,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('../../../_virtual/_tslib.cjs');
6
6
  var Client = require('@walletconnect/client');
7
- var ethers = require('ethers');
7
+ var viem = require('viem');
8
8
  var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
9
9
  var utils = require('@dynamic-labs/utils');
10
10
 
@@ -12,181 +12,184 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
12
12
 
13
13
  var Client__default = /*#__PURE__*/_interopDefaultLegacy(Client);
14
14
 
15
- const initClient = (name, bridge, settings) => {
16
- const storageId = `walletconnect-${name}`;
17
- const session = localStorage.getItem(storageId);
18
- const clientArgs = session
19
- ? { session: JSON.parse(session), storageId }
20
- : { bridge, storageId };
21
- return new Client__default["default"](Object.assign(Object.assign({}, clientArgs), settings));
22
- };
23
- /**
24
- * Attach event handlers to WalletConnect events.
25
- */
26
- const setupWalletConnectEventListeners = (opts, client) => {
27
- if (!client) {
28
- return;
29
- }
30
- let prevAccount;
31
- let prevChain;
32
- if (client.connected) {
33
- // eslint-disable-next-line prefer-destructuring
34
- prevAccount = client.accounts[0];
35
- prevChain = client.chainId;
36
- }
37
- client.on('disconnect', () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
38
- var _a;
39
- yield ((_a = opts.onDisconnect) === null || _a === void 0 ? void 0 : _a.call(opts));
40
- }));
41
- client.on('session_update', (_, payload) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
42
- var _b, _c;
43
- // eslint-disable-next-line prefer-destructuring
44
- const { accounts, chainId } = payload.params[0];
45
- const didAccountChange = !walletConnectorCore.isSameAddress(prevAccount || '', accounts[0], 'eip155');
46
- const didChainChange = prevChain !== chainId;
47
- // eslint-disable-next-line prefer-destructuring
48
- prevAccount = accounts[0];
49
- prevChain = chainId;
50
- if (didAccountChange) {
51
- yield ((_b = opts.onAccountChange) === null || _b === void 0 ? void 0 : _b.call(opts, accounts));
52
- }
53
- if (didChainChange) {
54
- yield ((_c = opts.onChainChange) === null || _c === void 0 ? void 0 : _c.call(opts, String(chainId)));
55
- }
56
- }));
57
- };
58
- const teardownWalletConnectEventListeners = (client) => {
59
- client.off('disconnect');
60
- client.off('session_update');
61
- };
62
- /**
63
- * Initialize a client from a stored session and terminate the connection.
64
- */
65
- const killWalletConnectSession = (client) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
66
- try {
67
- if (client === null || client === void 0 ? void 0 : client.connected) {
68
- yield client.killSession();
69
- }
70
- }
71
- catch (e) {
72
- walletConnectorCore.logger.debug(e);
73
- }
74
- });
75
- const createSession = (client) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
76
- return new Promise((resolve, reject) => {
77
- client.on('connect', (error, payload) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
78
- if (error)
79
- throw error;
80
- resolve(payload);
81
- }));
82
- client.on('disconnect', (error, payload) => {
83
- reject(error || payload.params[0].message);
84
- });
85
- });
86
- });
87
- const fetchWalletConnectEVMPublicAddress = (metadata, wcClient, opts) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
88
- var _a;
89
- if (wcClient.connected) {
90
- const [accountPublicAddress] = wcClient.accounts;
91
- return accountPublicAddress;
92
- }
93
- // createSession will trigger the QR code...
94
- yield wcClient.createSession();
95
- walletConnectorCore.performPlatformSpecificConnectionMethod(wcClient.uri, metadata, {
96
- onDesktopUri: opts === null || opts === void 0 ? void 0 : opts.onDesktopUri,
97
- onDisplayUri: opts === null || opts === void 0 ? void 0 : opts.onDisplayUri,
98
- });
99
- const payload = yield createSession(wcClient);
100
- (_a = opts === null || opts === void 0 ? void 0 : opts.onConnect) === null || _a === void 0 ? void 0 : _a.call(opts, payload);
101
- const [accountPublicAddress] = payload.params[0].accounts;
102
- return accountPublicAddress;
103
- });
104
- const signWalletConnectPersonalMessage = (messageToSign, metadata, client, rpcProvider) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
105
- var _b, _c;
106
- const isCryptoWallet = ((_b = client === null || client === void 0 ? void 0 : client.peerMeta) === null || _b === void 0 ? void 0 : _b.name) === 'Crypto.com | DeFi Wallet' ||
107
- ((_c = client === null || client === void 0 ? void 0 : client.peerMeta) === null || _c === void 0 ? void 0 : _c.name) === 'DeFi Wallet';
108
- if (!client || !client.connected) {
109
- return;
110
- }
111
- const [accountPublicAddress] = client.accounts;
112
- if (utils.isMobile()) {
113
- const deepLink = walletConnectorCore.getDeepLink({
114
- metadata,
115
- mode: 'regular',
116
- uri: client.uri,
117
- });
118
- window.location.href = deepLink;
119
- }
120
- try {
121
- // This delay is required for Crypto.com DeFi wallet, when there is no delay the app
122
- // will not open the pop-up to sign. That seems to be a limitation in the standalone client
123
- // so the delay is required to allow the users to sign the message
124
- if (isCryptoWallet && utils.isMobile()) {
125
- yield sleep(4000);
126
- }
127
- else {
128
- // The delay of 1 second is necessary for some of the wallets to open the sign UI in the
129
- // correct order, without this some wallets like Trust or OKX will no open properly,
130
- // and not allowing the user to sign the message
131
- yield sleep(1000);
132
- }
133
- const signature = yield client.signPersonalMessage([
134
- messageToSign,
135
- accountPublicAddress,
136
- ]);
137
- yield waitForSafeTransactionOrTimeout(accountPublicAddress, signature, messageToSign, client, rpcProvider);
138
- return signature;
139
- }
140
- catch (e) {
141
- walletConnectorCore.logger.debug(e);
142
- throw e;
143
- }
144
- });
145
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
146
- // Successful value as defined by the EIP
147
- // https://eips.ethereum.org/EIPS/eip-1271#specification
148
- const MAGIC_VALUE = '0x1626ba7e';
149
- const IS_VALID_SIGNATURE_ABI = [
150
- 'function isValidSignature(bytes32 _message, bytes _signature) public view returns (bytes4)',
151
- ];
152
- const waitForSafeTransactionOrTimeout = (accountPublicAddress, signature, messageToSign, client, rpcProvider) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
153
- var _d;
154
- if (signature === '0x' &&
155
- // this is what wallet connect client returns there's no `safe` or `Safe`
156
- // exact string anywhere, so this seems like the best proxy
157
- ((_d = client.peerMeta) === null || _d === void 0 ? void 0 : _d.name) === 'WalletConnect Safe App') {
158
- if (!rpcProvider) {
159
- return;
160
- }
161
- const contract = new ethers.Contract(accountPublicAddress, IS_VALID_SIGNATURE_ABI, yield rpcProvider());
162
- const safeTransactionPromise = waitForSafeTransaction(signature, messageToSign, contract);
163
- const timeoutPromise = new Promise((resolve) => {
164
- setTimeout(resolve, 120000);
165
- });
166
- yield Promise.race([safeTransactionPromise, timeoutPromise]);
167
- }
168
- });
169
- // this is a hack for safe
170
- // before sending the signature downstream, we need to make sure
171
- // the transaction is recorded first on the blockchain
172
- // redcoast verify WILL fail if it attempts to verify the signature
173
- // that has not yet been properly processed!
174
- const waitForSafeTransaction = (signature, messageToSign, contract) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
175
- // wait for safe wallet to finish txn on the blockchain contract
176
- for (let i = 0; i < 120; i++) {
177
- try {
178
- // this will result in an exception if the transaction is still not ready
179
- // we need to catch it below
180
- const result = yield contract.isValidSignature(ethers.ethers.utils.hashMessage(messageToSign), signature);
181
- if (result === MAGIC_VALUE)
182
- return;
183
- }
184
- catch (err) {
185
- walletConnectorCore.logger.info('Safe transaction cannot be validated yet. Retrying.');
186
- }
187
- // try again after 2 seconds
188
- yield sleep(2000);
189
- }
15
+ const initClient = (name, bridge, settings) => {
16
+ const storageId = `walletconnect-${name}`;
17
+ const session = localStorage.getItem(storageId);
18
+ const clientArgs = session
19
+ ? { session: JSON.parse(session), storageId }
20
+ : { bridge, storageId };
21
+ return new Client__default["default"](Object.assign(Object.assign({}, clientArgs), settings));
22
+ };
23
+ /**
24
+ * Attach event handlers to WalletConnect events.
25
+ */
26
+ const setupWalletConnectEventListeners = (walletConnector, client) => {
27
+ if (!client) {
28
+ return;
29
+ }
30
+ let prevAccount;
31
+ let prevChain;
32
+ if (client.connected) {
33
+ // eslint-disable-next-line prefer-destructuring
34
+ prevAccount = client.accounts[0];
35
+ prevChain = client.chainId;
36
+ }
37
+ client.on('disconnect', () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
38
+ walletConnector.emit('disconnect');
39
+ }));
40
+ client.on('session_update', (_, payload) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
41
+ // eslint-disable-next-line prefer-destructuring
42
+ const { accounts, chainId } = payload.params[0];
43
+ const didAccountChange = !walletConnectorCore.isSameAddress(prevAccount || '', accounts[0], 'eip155');
44
+ const didChainChange = prevChain !== chainId;
45
+ // eslint-disable-next-line prefer-destructuring
46
+ prevAccount = accounts[0];
47
+ prevChain = chainId;
48
+ if (didAccountChange) {
49
+ walletConnector.emit('accountChange', { accounts });
50
+ }
51
+ if (didChainChange) {
52
+ walletConnector.emit('chainChange', { chain: String(chainId) });
53
+ }
54
+ }));
55
+ };
56
+ const teardownWalletConnectEventListeners = (client) => {
57
+ client.off('disconnect');
58
+ client.off('session_update');
59
+ };
60
+ /**
61
+ * Initialize a client from a stored session and terminate the connection.
62
+ */
63
+ const killWalletConnectSession = (client) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
64
+ try {
65
+ if (client === null || client === void 0 ? void 0 : client.connected) {
66
+ yield client.killSession();
67
+ }
68
+ }
69
+ catch (e) {
70
+ walletConnectorCore.logger.debug(e);
71
+ }
72
+ });
73
+ const createSession = (client) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
74
+ return new Promise((resolve, reject) => {
75
+ client.on('connect', (error, payload) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
76
+ if (error)
77
+ throw error;
78
+ resolve(payload);
79
+ }));
80
+ client.on('disconnect', (error, payload) => {
81
+ reject(error || payload.params[0].message);
82
+ });
83
+ });
84
+ });
85
+ const fetchWalletConnectEVMPublicAddress = (metadata, wcClient, deepLinkPreference, opts) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
86
+ var _a;
87
+ if (wcClient.connected) {
88
+ const [accountPublicAddress] = wcClient.accounts;
89
+ return accountPublicAddress;
90
+ }
91
+ // createSession will trigger the QR code...
92
+ yield wcClient.createSession();
93
+ walletConnectorCore.performPlatformSpecificConnectionMethod(wcClient.uri, metadata, {
94
+ onDesktopUri: opts === null || opts === void 0 ? void 0 : opts.onDesktopUri,
95
+ onDisplayUri: opts === null || opts === void 0 ? void 0 : opts.onDisplayUri,
96
+ }, deepLinkPreference);
97
+ const payload = yield createSession(wcClient);
98
+ (_a = opts === null || opts === void 0 ? void 0 : opts.onConnect) === null || _a === void 0 ? void 0 : _a.call(opts, payload);
99
+ const [accountPublicAddress] = payload.params[0].accounts;
100
+ return accountPublicAddress;
101
+ });
102
+ const signWalletConnectPersonalMessage = (messageToSign, metadata, client, deepLinkPreference, rpcProvider) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
103
+ var _b, _c;
104
+ const isCryptoWallet = ((_b = client === null || client === void 0 ? void 0 : client.peerMeta) === null || _b === void 0 ? void 0 : _b.name) === 'Crypto.com | DeFi Wallet' ||
105
+ ((_c = client === null || client === void 0 ? void 0 : client.peerMeta) === null || _c === void 0 ? void 0 : _c.name) === 'DeFi Wallet';
106
+ if (!client || !client.connected) {
107
+ return;
108
+ }
109
+ const [accountPublicAddress] = client.accounts;
110
+ if (utils.isMobile()) {
111
+ const deepLink = walletConnectorCore.getDeepLink({
112
+ metadata,
113
+ mode: 'regular',
114
+ preference: deepLinkPreference,
115
+ uri: client.uri,
116
+ });
117
+ window.location.href = deepLink;
118
+ }
119
+ try {
120
+ // This delay is required for Crypto.com DeFi wallet, when there is no delay the app
121
+ // will not open the pop-up to sign. That seems to be a limitation in the standalone client
122
+ // so the delay is required to allow the users to sign the message
123
+ if (isCryptoWallet && utils.isMobile()) {
124
+ yield sleep(4000);
125
+ }
126
+ else {
127
+ // The delay of 1 second is necessary for some of the wallets to open the sign UI in the
128
+ // correct order, without this some wallets like Trust or OKX will no open properly,
129
+ // and not allowing the user to sign the message
130
+ yield sleep(1000);
131
+ }
132
+ const signature = yield client.signPersonalMessage([
133
+ messageToSign,
134
+ accountPublicAddress,
135
+ ]);
136
+ yield waitForSafeTransactionOrTimeout(accountPublicAddress, signature, messageToSign, client, rpcProvider);
137
+ return signature;
138
+ }
139
+ catch (e) {
140
+ walletConnectorCore.logger.debug(e);
141
+ throw e;
142
+ }
143
+ });
144
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
145
+ // Successful value as defined by the EIP
146
+ // https://eips.ethereum.org/EIPS/eip-1271#specification
147
+ const MAGIC_VALUE = '0x1626ba7e';
148
+ const IS_VALID_SIGNATURE_ABI = [
149
+ 'function isValidSignature(bytes32 _message, bytes _signature) public view returns (bytes4)',
150
+ ];
151
+ const waitForSafeTransactionOrTimeout = (accountPublicAddress, signature, messageToSign, client, rpcProvider) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
152
+ var _d;
153
+ if (signature === '0x' &&
154
+ // this is what wallet connect client returns there's no `safe` or `Safe`
155
+ // exact string anywhere, so this seems like the best proxy
156
+ ((_d = client.peerMeta) === null || _d === void 0 ? void 0 : _d.name) === 'WalletConnect Safe App') {
157
+ if (!rpcProvider) {
158
+ return;
159
+ }
160
+ const safeTransactionPromise = waitForSafeTransaction(accountPublicAddress, signature, messageToSign, yield rpcProvider());
161
+ const timeoutPromise = new Promise((resolve) => {
162
+ setTimeout(resolve, 120000);
163
+ });
164
+ yield Promise.race([safeTransactionPromise, timeoutPromise]);
165
+ }
166
+ });
167
+ // this is a hack for safe
168
+ // before sending the signature downstream, we need to make sure
169
+ // the transaction is recorded first on the blockchain
170
+ // redcoast verify WILL fail if it attempts to verify the signature
171
+ // that has not yet been properly processed!
172
+ const waitForSafeTransaction = (accountPublicAddress, signature, messageToSign, rpcProvider) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
173
+ // wait for safe wallet to finish txn on the blockchain contract
174
+ for (let i = 0; i < 120; i++) {
175
+ try {
176
+ // this will result in an exception if the transaction is still not ready
177
+ // we need to catch it below
178
+ const result = yield (rpcProvider === null || rpcProvider === void 0 ? void 0 : rpcProvider.readContract({
179
+ abi: IS_VALID_SIGNATURE_ABI,
180
+ address: accountPublicAddress,
181
+ args: [viem.hashMessage(messageToSign), signature],
182
+ functionName: 'isValidSignature',
183
+ }));
184
+ if (result === MAGIC_VALUE)
185
+ return;
186
+ }
187
+ catch (err) {
188
+ walletConnectorCore.logger.info('Safe transaction cannot be validated yet. Retrying.');
189
+ }
190
+ // try again after 2 seconds
191
+ yield sleep(2000);
192
+ }
190
193
  });
191
194
 
192
195
  exports.createSession = createSession;