@toruslabs/ethereum-controllers 9.3.0 → 9.4.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.
@@ -3,7 +3,6 @@
3
3
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
4
4
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
5
5
  var baseControllers = require('@toruslabs/base-controllers');
6
- var httpHelpers = require('@toruslabs/http-helpers');
7
6
  var log = require('loglevel');
8
7
 
9
8
  class CurrencyController extends baseControllers.BaseCurrencyController {
@@ -11,13 +10,15 @@ class CurrencyController extends baseControllers.BaseCurrencyController {
11
10
  config,
12
11
  state,
13
12
  idleTimeTracker,
14
- onNetworkChanged
13
+ onNetworkChanged,
14
+ getAuthHttpClient
15
15
  }) {
16
16
  super({
17
17
  config,
18
18
  state
19
19
  });
20
20
  _defineProperty(this, "pollingManager", void 0);
21
+ _defineProperty(this, "getAuthHttpClient", void 0);
21
22
  this.defaultState = _objectSpread(_objectSpread({}, this.defaultState), {}, {
22
23
  commonDenomination: "USD",
23
24
  commonDenominatorPrice: 0
@@ -30,6 +31,7 @@ class CurrencyController extends baseControllers.BaseCurrencyController {
30
31
  this.updateConversionRate();
31
32
  }
32
33
  });
34
+ this.getAuthHttpClient = getAuthHttpClient;
33
35
  this.pollingManager = new baseControllers.PollingManager(idleTimeTracker, this.config.pollInterval);
34
36
  }
35
37
  setCommonDenomination(commonDenomination) {
@@ -84,11 +86,14 @@ class CurrencyController extends baseControllers.BaseCurrencyController {
84
86
  }
85
87
  async retrieveConversionRate(fromCurrency, toCurrency, commonDenomination) {
86
88
  try {
87
- let apiUrl = `${this.config.api}/currency?fsym=${fromCurrency.toUpperCase()}&tsyms=${toCurrency.toUpperCase()}`;
89
+ const httpClient = baseControllers.resolveAuthHttpClient(this.getAuthHttpClient, this.name);
90
+ let apiUrl = `${this.config.api}/v2/currency?fsym=${fromCurrency.toUpperCase()}&tsyms=${toCurrency.toUpperCase()}`;
88
91
  if (commonDenomination && commonDenomination.toUpperCase() !== toCurrency.toUpperCase()) {
89
92
  apiUrl += `,${commonDenomination.toUpperCase()}`;
90
93
  }
91
- const parsedResponse = await httpHelpers.get(apiUrl);
94
+ const parsedResponse = await httpClient.get(apiUrl, {
95
+ authenticated: true
96
+ });
92
97
  return parsedResponse;
93
98
  } catch (error) {
94
99
  log.error(error, `CurrencyController - updateCommonDenominatorPrice: Failed to query rate for currency: ${fromCurrency}/ ${toCurrency}`);
@@ -5,32 +5,28 @@ var baseControllers = require('@toruslabs/base-controllers');
5
5
  var metadataHelpers = require('@toruslabs/metadata-helpers');
6
6
  var log = require('loglevel');
7
7
  var constants = require('../utils/constants.js');
8
- var helpers = require('../utils/helpers.js');
9
8
 
10
9
  class PreferencesController extends baseControllers.BasePreferencesController {
11
10
  constructor({
12
11
  config,
13
12
  state,
14
- provider,
15
13
  signAuthMessage,
16
14
  getProviderConfig,
17
15
  setProviderConfig,
18
- validateSignMessage
16
+ validateSignMessage,
17
+ getAuthHttpClient
19
18
  }) {
20
19
  super({
21
20
  config,
22
21
  state,
23
- defaultPreferences: {
24
- etherscanTransactions: []
25
- },
22
+ defaultPreferences: {},
26
23
  signAuthMessage,
27
- validateSignMessage
24
+ validateSignMessage,
25
+ getAuthHttpClient
28
26
  });
29
27
  _defineProperty(this, "chainNamespace", baseControllers.CHAIN_NAMESPACES.EIP155);
30
28
  _defineProperty(this, "getProviderConfig", void 0);
31
29
  _defineProperty(this, "setProviderConfig", void 0);
32
- _defineProperty(this, "provider", void 0);
33
- this.provider = provider;
34
30
  this.getProviderConfig = getProviderConfig;
35
31
  this.setProviderConfig = setProviderConfig;
36
32
  }
@@ -38,15 +34,12 @@ class PreferencesController extends baseControllers.BasePreferencesController {
38
34
  const {
39
35
  address,
40
36
  jwtToken,
41
- calledFromEmbed,
37
+ accessToken,
38
+ origin,
42
39
  userInfo,
43
- rehydrate,
44
40
  type,
45
41
  signatures,
46
- web3AuthClientId,
47
42
  web3AuthNetwork,
48
- loginMode,
49
- sessionPubKey,
50
43
  aaProvider,
51
44
  eoaAddress,
52
45
  mainAddress
@@ -58,6 +51,8 @@ class PreferencesController extends baseControllers.BasePreferencesController {
58
51
  address,
59
52
  userInfo,
60
53
  idToken: jwtToken,
54
+ accessToken,
55
+ origin,
61
56
  type,
62
57
  metadata: {
63
58
  email: userInfo.email,
@@ -69,74 +64,19 @@ class PreferencesController extends baseControllers.BasePreferencesController {
69
64
  main_address: mainAddress
70
65
  }
71
66
  });
72
- const {
73
- groupedAuthConnectionId,
74
- authConnectionId,
75
- userId
76
- } = userInfo || {};
77
67
  if (eoaAddress) this.updateState({
78
68
  eoaAddress
79
69
  }, address);
80
- this.storeUserLogin({
81
- groupedAuthConnectionId,
82
- authConnectionId,
83
- userId,
84
- options: {
85
- calledFromEmbed,
86
- rehydrate
87
- },
88
- address,
89
- web3AuthClientId,
90
- web3AuthNetwork,
91
- sessionPubKey,
92
- loginMode
93
- });
94
70
  }
95
71
  getSelectedAddress() {
96
72
  return this.state.selectedAddress;
97
73
  }
98
- async refetchEtherscanTx(address) {
99
- var _this$getAddressState;
100
- const selectedAddress = address || this.state.selectedAddress;
101
- if (!selectedAddress) return [];
102
- if ((_this$getAddressState = this.getAddressState(selectedAddress)) !== null && _this$getAddressState !== void 0 && _this$getAddressState.jwtToken) {
103
- const {
104
- chainId
105
- } = this.getProviderConfig();
106
- if (constants.MM_TOKEN_API_SUPPORTED_CHAINS.includes(chainId)) {
107
- const lowerCaseSelectedAddress = selectedAddress.toLowerCase();
108
- const etherscanTxn = await this.fetchEtherscanTx({
109
- selectedAddress,
110
- chainId: this.getProviderConfig().chainId
111
- });
112
- const finalEthScanTxn = await helpers.addEtherscanTransactions({
113
- txn: etherscanTxn,
114
- lowerCaseSelectedAddress,
115
- provider: this.provider,
116
- chainId,
117
- blockExplorerUrl: this.getBlockExplorerUrl()
118
- });
119
- log.info("Formatted Etherscan Response", finalEthScanTxn);
120
- this.updateState({
121
- etherscanTransactions: finalEthScanTxn
122
- });
123
- return etherscanTxn;
124
- }
125
- }
126
- }
127
- async fetchEtherscanTx(parameters) {
128
- try {
129
- const response = await this.wsApiClient.authGet(`etherscan?chainId=${parameters.chainId}`, this.authCredentials(parameters.selectedAddress));
130
- log.info("Etherscan Response API", response);
131
- return response.success ? response.data : [];
132
- } catch (error) {
133
- log.error("unable to fetch etherscan tx", error);
134
- return [];
135
- }
136
- }
137
74
  async fetchQuote(parameters) {
138
75
  try {
139
- const response = await this.wsApiClient.authPost("quote", parameters, this.authCredentials());
76
+ const response = await this.getAuthHttpClient().post(`${this.config.api}/v2/quote`, parameters, {
77
+ authenticated: true,
78
+ headers: this.constructAuthHeaders()
79
+ });
140
80
  return response.success ? response.data : [];
141
81
  } catch (error) {
142
82
  log.error("unable to get swap quote", error);
@@ -145,29 +85,36 @@ class PreferencesController extends baseControllers.BasePreferencesController {
145
85
  }
146
86
  async getEtherScanTokens(address, chainId, skipCache) {
147
87
  const selectedAddress = address;
148
- let path = `tokens?chainId=${chainId}&address=${selectedAddress}`;
88
+ let path = `v2/tokens?chainId=${chainId}&address=${selectedAddress}`;
149
89
  if (skipCache) {
150
90
  path += `&skipCache=true`;
151
91
  }
152
- const result = await this.wsApiClient.authGet(path, this.authCredentials());
92
+ // TODO: pass selected address as headers and not as a query parameter
93
+ const result = await this.getAuthHttpClient().get(`${this.config.api}/${path}`, {
94
+ authenticated: true
95
+ });
153
96
  return result.data;
154
97
  }
155
98
  async getSimpleHashNfts(address, chainId, skipCache) {
156
99
  const selectedAddress = address;
157
- let path = `nfts?chainId=${chainId}&address=${selectedAddress}`;
100
+ let path = `v2/nfts?chainId=${chainId}&address=${selectedAddress}`;
158
101
  if (skipCache) {
159
102
  path += `&skipCache=true`;
160
103
  }
161
- const result = await this.wsApiClient.authGet(path, this.authCredentials());
104
+ // TODO: pass selected address as headers and not as a query parameter
105
+ const result = await this.getAuthHttpClient().get(`${this.config.api}/${path}`, {
106
+ authenticated: true,
107
+ headers: this.constructAuthHeaders()
108
+ });
162
109
  return result.data;
163
110
  }
164
111
  getCustomTokens(address) {
165
- var _this$getAddressState2, _this$getAddressState3;
166
- return (_this$getAddressState2 = (_this$getAddressState3 = this.getAddressState(address)) === null || _this$getAddressState3 === void 0 ? void 0 : _this$getAddressState3.customTokens) !== null && _this$getAddressState2 !== void 0 ? _this$getAddressState2 : [];
112
+ var _this$getAddressState, _this$getAddressState2;
113
+ return (_this$getAddressState = (_this$getAddressState2 = this.getAddressState(address)) === null || _this$getAddressState2 === void 0 ? void 0 : _this$getAddressState2.customTokens) !== null && _this$getAddressState !== void 0 ? _this$getAddressState : [];
167
114
  }
168
115
  getCustomNfts(address) {
169
- var _this$getAddressState4, _this$getAddressState5;
170
- return (_this$getAddressState4 = (_this$getAddressState5 = this.getAddressState(address)) === null || _this$getAddressState5 === void 0 ? void 0 : _this$getAddressState5.customNfts) !== null && _this$getAddressState4 !== void 0 ? _this$getAddressState4 : [];
116
+ var _this$getAddressState3, _this$getAddressState4;
117
+ return (_this$getAddressState3 = (_this$getAddressState4 = this.getAddressState(address)) === null || _this$getAddressState4 === void 0 ? void 0 : _this$getAddressState4.customNfts) !== null && _this$getAddressState3 !== void 0 ? _this$getAddressState3 : [];
171
118
  }
172
119
  // NOTE: keep address params for now, might need to handle aa addresses later
173
120
  isChainIdSupported(_address, chainId) {
@@ -193,12 +140,6 @@ class PreferencesController extends baseControllers.BasePreferencesController {
193
140
  getChainOptions() {
194
141
  return Object.values(constants.SUPPORTED_NETWORKS);
195
142
  }
196
- getBlockExplorerUrl() {
197
- const supportedNetworks = this.getChainOptions();
198
- const network = supportedNetworks.find(x => x.chainId === this.getProviderConfig().chainId);
199
- if (!network) return "";
200
- return `${network.blockExplorerUrl}`;
201
- }
202
143
  }
203
144
 
204
145
  exports.PreferencesController = PreferencesController;
@@ -3,7 +3,6 @@
3
3
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
4
4
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
5
5
  var baseControllers = require('@toruslabs/base-controllers');
6
- var httpHelpers = require('@toruslabs/http-helpers');
7
6
  var log = require('loglevel');
8
7
  var constants = require('../utils/constants.js');
9
8
 
@@ -15,13 +14,15 @@ class TokenRatesController extends baseControllers.BaseController {
15
14
  idleTimeTracker,
16
15
  onPreferencesStateChange,
17
16
  onNetworkStateChange,
18
- onTokensStateChange
17
+ onTokensStateChange,
18
+ getAuthHttpClient
19
19
  }) {
20
20
  super({
21
21
  config,
22
22
  state
23
23
  });
24
24
  _defineProperty(this, "pollingManager", void 0);
25
+ _defineProperty(this, "getAuthHttpClient", void 0);
25
26
  this.defaultState = _objectSpread(_objectSpread({}, this.defaultState), {}, {
26
27
  contractExchangeRates: {}
27
28
  });
@@ -49,17 +50,18 @@ class TokenRatesController extends baseControllers.BaseController {
49
50
  tokens
50
51
  } = tokensState;
51
52
  const currentUserTokens = tokens[this.config.selectedAddress];
52
- if ((currentUserTokens === null || currentUserTokens === void 0 ? void 0 : currentUserTokens.length) > 0 && this.config.tokens !== tokens[this.config.selectedAddress]) {
53
+ if ((currentUserTokens === null || currentUserTokens === void 0 ? void 0 : currentUserTokens.length) > 0 && this.config.tokens !== currentUserTokens) {
53
54
  this.configure({
54
- tokens: tokens[this.config.selectedAddress]
55
+ tokens: currentUserTokens
55
56
  });
56
57
  this.updateExchangeRates();
57
58
  }
58
59
  });
60
+ this.getAuthHttpClient = getAuthHttpClient;
59
61
  this.pollingManager = new baseControllers.PollingManager(idleTimeTracker, this.config.pollInterval);
60
62
  }
61
63
  /**
62
- * Creates a new poll, using setInterval, to periodically call updateConversionRate. The id of the interval is
64
+ * Creates a new poll, using setInterval, to periodically call updateExchangeRates. The id of the interval is
63
65
  * stored at the controller's conversionInterval property. If it is called and such an id already exists, the
64
66
  * previous interval is clear and a new one is created.
65
67
  */
@@ -82,17 +84,24 @@ class TokenRatesController extends baseControllers.BaseController {
82
84
  });
83
85
  }
84
86
  async fetchExchangeRates(nativeCurrency, chainCodes) {
87
+ const httpClient = baseControllers.resolveAuthHttpClient(this.getAuthHttpClient, this.name);
85
88
  const contractAddresses = this.config.tokens.map(token => token.tokenAddress);
86
89
  const isNativeCurrencySupported = constants.COINGECKO_SUPPORTED_CURRENCIES.has(nativeCurrency.toLowerCase());
87
90
  if (isNativeCurrencySupported) {
88
- const response = await httpHelpers.get(`${this.config.currencyApi}/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${nativeCurrency.toLowerCase()}`);
91
+ const response = await httpClient.get(`${this.config.currencyApi}/v2/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${nativeCurrency.toLowerCase()}`, {
92
+ authenticated: true
93
+ });
89
94
  const newContractExchangeRates = {};
90
95
  Object.keys(response).forEach(contractAddress => {
91
96
  newContractExchangeRates[contractAddress] = response[contractAddress][nativeCurrency.toLowerCase()] || 0;
92
97
  });
93
98
  return newContractExchangeRates;
94
99
  }
95
- const [response, currencyResponse] = await Promise.all([httpHelpers.get(`${this.config.currencyApi}/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${DEFAULT_CURRENCY}`), httpHelpers.get(`${this.config.currencyApi}/currency?fsym=${nativeCurrency.toUpperCase()}&tsyms=${DEFAULT_CURRENCY.toUpperCase()}`)]);
100
+ const [response, currencyResponse] = await Promise.all([httpClient.get(`${this.config.currencyApi}/v2/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${DEFAULT_CURRENCY}`, {
101
+ authenticated: true
102
+ }), httpClient.get(`${this.config.currencyApi}/v2/currency?fsym=${nativeCurrency.toUpperCase()}&tsyms=${DEFAULT_CURRENCY.toUpperCase()}`, {
103
+ authenticated: true
104
+ })]);
96
105
  const newContractExchangeRates = {};
97
106
  Object.keys(response).forEach(contractAddress => {
98
107
  newContractExchangeRates[contractAddress] = response[contractAddress][DEFAULT_CURRENCY] * Number.parseFloat(currencyResponse[DEFAULT_CURRENCY]) || 0;
@@ -220,10 +220,8 @@ exports.EIP_7702_PREFIX = eip7702Types.EIP_7702_PREFIX;
220
220
  exports.EIP_7702_REVOKE_ADDRESS = eip7702Types.EIP_7702_REVOKE_ADDRESS;
221
221
  exports.BNToHex = helpers.BNToHex;
222
222
  exports.GAS_LIMITS = helpers.GAS_LIMITS;
223
- exports.addEtherscanTransactions = helpers.addEtherscanTransactions;
224
223
  exports.bnLessThan = helpers.bnLessThan;
225
224
  exports.formatDate = helpers.formatDate;
226
- exports.formatPastTx = helpers.formatPastTx;
227
225
  exports.formatTime = helpers.formatTime;
228
226
  exports.getChainType = helpers.getChainType;
229
227
  exports.getEthTxStatus = helpers.getEthTxStatus;
@@ -1,4 +1,4 @@
1
- import { BaseCurrencyController, BaseCurrencyControllerConfig, BaseCurrencyControllerState, ICurrencyController, IdleTimeTracker } from "@toruslabs/base-controllers";
1
+ import { AuthHttpClientGetter, BaseCurrencyController, BaseCurrencyControllerConfig, BaseCurrencyControllerState, ICurrencyController, IdleTimeTracker } from "@toruslabs/base-controllers";
2
2
  import { EthereumNetworkState } from "../utils/interfaces";
3
3
  export interface IEthereumCurrencyControllerState extends BaseCurrencyControllerState {
4
4
  commonDenomination: string;
@@ -6,11 +6,13 @@ export interface IEthereumCurrencyControllerState extends BaseCurrencyController
6
6
  }
7
7
  export declare class CurrencyController extends BaseCurrencyController<BaseCurrencyControllerConfig, IEthereumCurrencyControllerState> implements ICurrencyController<BaseCurrencyControllerConfig, IEthereumCurrencyControllerState> {
8
8
  private pollingManager;
9
- constructor({ config, state, idleTimeTracker, onNetworkChanged, }: {
9
+ private readonly getAuthHttpClient;
10
+ constructor({ config, state, idleTimeTracker, onNetworkChanged, getAuthHttpClient, }: {
10
11
  config: Partial<BaseCurrencyControllerConfig>;
11
12
  state: Partial<IEthereumCurrencyControllerState>;
12
13
  idleTimeTracker: IdleTimeTracker;
13
14
  onNetworkChanged: (listener: (networkState: EthereumNetworkState) => void) => void;
15
+ getAuthHttpClient: AuthHttpClientGetter;
14
16
  });
15
17
  setCommonDenomination(commonDenomination: string): void;
16
18
  getCommonDenomination(): string;
@@ -1,6 +1,4 @@
1
1
  import { AddressPreferences } from "@toruslabs/base-controllers";
2
- import { FormattedTransactionActivity } from "../utils/interfaces";
3
2
  export interface ExtendedAddressPreferences extends AddressPreferences {
4
3
  eoaAddress?: string;
5
- etherscanTransactions?: FormattedTransactionActivity[];
6
4
  }
@@ -1,36 +1,29 @@
1
- import { BasePreferencesController, CustomNft, CustomToken, InitPreferencesParams, IPreferencesController, PreferencesConfig, PreferencesState } from "@toruslabs/base-controllers";
2
- import { SafeEventEmitterProvider } from "@web3auth/auth";
1
+ import { AuthHttpClientGetter, BasePreferencesController, CustomNft, CustomToken, InitPreferencesParams, IPreferencesController, PreferencesConfig, PreferencesState } from "@toruslabs/base-controllers";
3
2
  import { KeyringController } from "../Keyring/KeyringController";
4
3
  import { NetworkController } from "../Network/NetworkController";
5
4
  import { EthereumNftInfo as CustomNftInfo } from "../Nfts/INftsController";
6
- import type { AddChainMessageParams, CustomTokenInfo, EtherscanTransaction } from "../utils/interfaces";
5
+ import type { AddChainMessageParams, CustomTokenInfo } from "../utils/interfaces";
7
6
  import { ExtendedAddressPreferences } from "./IPreferencesController";
8
7
  export interface IPreferencesControllerOptions {
9
8
  config?: Partial<PreferencesConfig> & Pick<PreferencesConfig, "api" | "commonApiHost">;
10
9
  state?: Partial<PreferencesState<ExtendedAddressPreferences>>;
11
- provider: SafeEventEmitterProvider;
12
10
  signAuthMessage?: KeyringController["signAuthMessage"];
13
11
  getProviderConfig?: NetworkController["getProviderConfig"];
14
12
  setProviderConfig?: NetworkController["setProviderConfig"];
15
13
  validateSignMessage: (message: string) => Promise<void>;
14
+ getAuthHttpClient: AuthHttpClientGetter;
16
15
  }
17
16
  export declare class PreferencesController extends BasePreferencesController<ExtendedAddressPreferences, PreferencesConfig, PreferencesState<ExtendedAddressPreferences>> implements IPreferencesController<ExtendedAddressPreferences, PreferencesConfig, PreferencesState<ExtendedAddressPreferences>> {
18
17
  protected chainNamespace: "eip155";
19
18
  private getProviderConfig;
20
19
  private setProviderConfig;
21
- private provider;
22
- constructor({ config, state, provider, signAuthMessage, getProviderConfig, setProviderConfig, validateSignMessage, }: IPreferencesControllerOptions);
20
+ constructor({ config, state, signAuthMessage, getProviderConfig, setProviderConfig, validateSignMessage, getAuthHttpClient, }: IPreferencesControllerOptions);
23
21
  initPreferences(params: InitPreferencesParams & {
24
22
  eoaAddress?: string;
25
23
  aaProvider?: string;
26
24
  mainAddress?: string;
27
25
  }): Promise<void>;
28
26
  getSelectedAddress(): string;
29
- refetchEtherscanTx(address?: string): Promise<EtherscanTransaction[]>;
30
- fetchEtherscanTx<T>(parameters: {
31
- selectedAddress: string;
32
- chainId: string;
33
- }): Promise<T[]>;
34
27
  fetchQuote<T>(parameters: {
35
28
  chainId: string;
36
29
  fromToken: string;
@@ -57,5 +50,4 @@ export declare class PreferencesController extends BasePreferencesController<Ext
57
50
  chainId: string;
58
51
  }): void;
59
52
  private getChainOptions;
60
- private getBlockExplorerUrl;
61
53
  }
@@ -1,4 +1,4 @@
1
- import { BaseController, BaseTokenRatesControllerConfig, BaseTokenRatesControllerState, IdleTimeTracker, ITokenRatesController, PreferencesState } from "@toruslabs/base-controllers";
1
+ import { AuthHttpClientGetter, BaseController, BaseTokenRatesControllerConfig, BaseTokenRatesControllerState, IdleTimeTracker, ITokenRatesController, PreferencesState } from "@toruslabs/base-controllers";
2
2
  import { ExtendedAddressPreferences } from "../Preferences/IPreferencesController";
3
3
  import { CustomTokenInfo, EthereumNetworkState } from "../utils/interfaces";
4
4
  import { EthereumTokensControllerState } from "./ITokensController";
@@ -20,12 +20,14 @@ export interface TokenRatesControllerOptions {
20
20
  onPreferencesStateChange: (listener: (preferencesState: PreferencesState<ExtendedAddressPreferences>) => void) => void;
21
21
  onTokensStateChange: (listener: (tokensState: EthereumTokensControllerState) => void) => void;
22
22
  onNetworkStateChange: (listener: (networkState: EthereumNetworkState) => void) => void;
23
+ getAuthHttpClient: AuthHttpClientGetter;
23
24
  }
24
25
  export declare class TokenRatesController extends BaseController<ITokenRatesControllerConfig, ITokenRatesControllerState> implements ITokenRatesController<ITokenRatesControllerConfig, ITokenRatesControllerState> {
25
26
  private pollingManager;
26
- constructor({ config, state, idleTimeTracker, onPreferencesStateChange, onNetworkStateChange, onTokensStateChange }: TokenRatesControllerOptions);
27
+ private readonly getAuthHttpClient;
28
+ constructor({ config, state, idleTimeTracker, onPreferencesStateChange, onNetworkStateChange, onTokensStateChange, getAuthHttpClient, }: TokenRatesControllerOptions);
27
29
  /**
28
- * Creates a new poll, using setInterval, to periodically call updateConversionRate. The id of the interval is
30
+ * Creates a new poll, using setInterval, to periodically call updateExchangeRates. The id of the interval is
29
31
  * stored at the controller's conversionInterval property. If it is called and such an id already exists, the
30
32
  * previous interval is clear and a new one is created.
31
33
  */
@@ -1,14 +1,8 @@
1
1
  import { TransactionStatus } from "@toruslabs/base-controllers";
2
2
  import { SafeEventEmitterProvider } from "@web3auth/auth";
3
- import { EtherscanTransaction, FormattedTransactionActivity, TransactionPayload } from "./interfaces";
4
3
  export declare function hexToBn(hex: string): BigNumber;
5
4
  export declare function BNToHex(bn: BigNumber): string;
6
5
  export declare function getEtherScanHashLink(txHash: string, chainId: string): string;
7
- export declare const formatPastTx: (params: {
8
- transaction: TransactionPayload;
9
- blockExplorerUrl: string;
10
- lowerCaseSelectedAddress?: string;
11
- }) => FormattedTransactionActivity;
12
6
  /**
13
7
  * Ref - https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt
14
8
  */
@@ -25,10 +19,3 @@ export declare function bnLessThan(a: string | number, b: string | number): bool
25
19
  export declare const getIpfsEndpoint: (path: string) => string;
26
20
  export declare function sanitizeNftMetdataUrl(url: string): string;
27
21
  export declare function getChainType(chainId: string): "custom" | "mainnet" | "testnet";
28
- export declare const addEtherscanTransactions: (params: {
29
- txn: EtherscanTransaction[];
30
- lowerCaseSelectedAddress: string;
31
- provider: SafeEventEmitterProvider;
32
- chainId: string;
33
- blockExplorerUrl: string;
34
- }) => Promise<any[]>;
@@ -1,5 +1,5 @@
1
1
  import { Implementation, toMetaMaskSmartAccount } from "@metamask/smart-accounts-kit";
2
- import { BASE_TX_EVENT_TYPE, BaseBlockTrackerState, BaseControllerEvents, BaseFormattedTransactionActivity, BaseTokenInfo, BaseTransactionEvents, MESSAGE_EVENTS, MessageStatus, NetworkConfig, NetworkState, PaymentTransaction, PollingBlockTrackerConfig, PopupWhitelabelData, ProviderConfig, TRANSACTION_TYPE, TransactionMeta, TransactionState, TransactionStatus, TX_CONFIRMED_EVENT_TYPE, TX_DROPPED_EVENT_TYPE, TX_EVENTS, TX_FAILED_EVENT_TYPE, TX_WARNING_EVENT_TYPE } from "@toruslabs/base-controllers";
2
+ import { BASE_TX_EVENT_TYPE, BaseBlockTrackerState, BaseControllerEvents, BaseTokenInfo, BaseTransactionEvents, MESSAGE_EVENTS, MessageStatus, NetworkConfig, NetworkState, PaymentTransaction, PollingBlockTrackerConfig, PopupWhitelabelData, ProviderConfig, TRANSACTION_TYPE, TransactionMeta, TransactionState, TransactionStatus, TX_CONFIRMED_EVENT_TYPE, TX_DROPPED_EVENT_TYPE, TX_EVENTS, TX_FAILED_EVENT_TYPE, TX_WARNING_EVENT_TYPE } from "@toruslabs/base-controllers";
3
3
  import { JRPCRequest, Json } from "@web3auth/auth";
4
4
  import { MutexInterface } from "async-mutex";
5
5
  import { ToBiconomySmartAccountParameters, toEcdsaKernelSmartAccount, ToLightSmartAccountParameters, ToNexusSmartAccountParameters, toSafeSmartAccount, toSimpleSmartAccount, toTrustSmartAccount } from "permissionless/accounts";
@@ -337,17 +337,6 @@ export interface FetchedTransaction extends TransactionPayload {
337
337
  export interface FetchCommonTransaction extends PaymentTransaction {
338
338
  etherscanLink?: string | null;
339
339
  }
340
- export interface FormattedTransactionActivity extends BaseFormattedTransactionActivity {
341
- from_aa_address?: string;
342
- etherscanLink: string;
343
- ethRate: string;
344
- isEtherscan?: boolean;
345
- nonce: string;
346
- gas: string;
347
- gasPrice: string;
348
- cancelGas?: string;
349
- cancelGasPrice?: string;
350
- }
351
340
  export interface ProviderChangeChannelEventData {
352
341
  newNetwork: EthereumProviderConfig;
353
342
  whitelabelData: PopupWhitelabelData;
@@ -360,38 +349,6 @@ export interface NonceLockRes {
360
349
  releaseLock: MutexInterface.Releaser;
361
350
  }
362
351
  export type METHOD_TYPES_TYPE = (typeof METHOD_TYPES)[keyof typeof METHOD_TYPES];
363
- export interface EtherscanTransaction {
364
- blockNumber: string;
365
- timeStamp: string;
366
- hash: string;
367
- nonce: string;
368
- blockHash: string;
369
- transactionIndex: string;
370
- from: string;
371
- to: string;
372
- value: string;
373
- gas: string;
374
- gasPrice: string;
375
- isError: string;
376
- txreceipt_status: string;
377
- input: string;
378
- contractAddress: string;
379
- cumulativeGasUsed: string;
380
- gasUsed: string;
381
- confirmations: string;
382
- methodId: string;
383
- functionName: string;
384
- transaction_category: string;
385
- type_name: string;
386
- type: string;
387
- type_image_link: string;
388
- chainId: string;
389
- tokenSymbol: string;
390
- tokenName: string;
391
- tokenID: string;
392
- tokenValue: string;
393
- tokenDecimal: string;
394
- }
395
352
  export interface NetworkControllerEvents<S> extends BaseControllerEvents<S> {
396
353
  networkDidChange: () => void;
397
354
  }
@@ -1,12 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
4
3
  var baseControllers = require('@toruslabs/base-controllers');
5
4
  var metadataHelpers = require('@toruslabs/metadata-helpers');
6
5
  var bignumber_js = require('bignumber.js');
7
6
  var log = require('loglevel');
8
7
  var viem = require('viem');
9
- var TransactionUtils = require('../Transaction/TransactionUtils.js');
10
8
  var constants = require('./constants.js');
11
9
 
12
10
  function hexToBn(hex) {
@@ -19,51 +17,6 @@ function getEtherScanHashLink(txHash, chainId) {
19
17
  if (!constants.SUPPORTED_NETWORKS[chainId]) return "";
20
18
  return `${constants.SUPPORTED_NETWORKS[chainId].blockExplorerUrl}/tx/${txHash}`;
21
19
  }
22
- const formatPastTx = params => {
23
- var _transaction$to;
24
- const {
25
- transaction,
26
- lowerCaseSelectedAddress,
27
- blockExplorerUrl
28
- } = params;
29
- let totalAmountString = "";
30
- if (transaction.type === constants.CONTRACT_TYPE_ERC721 || transaction.type === constants.CONTRACT_TYPE_ERC1155) totalAmountString = transaction.symbol;else if (transaction.type === constants.CONTRACT_TYPE_ERC20) totalAmountString = baseControllers.formatSmallNumbers(Number.parseFloat(transaction.total_amount), transaction.symbol, true);else totalAmountString = baseControllers.formatSmallNumbers(Number.parseFloat(transaction.total_amount), transaction.type_name, true);
31
- const currencyAmountString = transaction.type === constants.CONTRACT_TYPE_ERC721 || transaction.type === constants.CONTRACT_TYPE_ERC1155 || transaction.isEtherscan ? "" : baseControllers.formatSmallNumbers(Number.parseFloat(transaction.currency_amount), transaction.selected_currency, true);
32
- const finalObject = {
33
- id: transaction.created_at.toString(),
34
- date: new Date(transaction.created_at).toString(),
35
- from: transaction.from,
36
- from_aa_address: transaction.from_aa_address,
37
- slicedFrom: typeof transaction.from === "string" ? baseControllers.addressSlicer(transaction.from) : "",
38
- to: transaction.to,
39
- slicedTo: typeof transaction.to === "string" ? baseControllers.addressSlicer(transaction.to) : "",
40
- action: lowerCaseSelectedAddress === ((_transaction$to = transaction.to) === null || _transaction$to === void 0 ? void 0 : _transaction$to.toLowerCase()) || "" ? baseControllers.ACTIVITY_ACTION_RECEIVE : baseControllers.ACTIVITY_ACTION_SEND,
41
- totalAmount: transaction.total_amount,
42
- totalAmountString,
43
- currencyAmount: transaction.currency_amount,
44
- currencyAmountString,
45
- amount: `${totalAmountString} / ${currencyAmountString}`,
46
- status: transaction.status,
47
- etherscanLink: blockExplorerUrl ? `${blockExplorerUrl}/tx/${transaction.transaction_hash}` : "",
48
- chainId: transaction.chain_id,
49
- ethRate: Number.parseFloat(transaction === null || transaction === void 0 ? void 0 : transaction.total_amount) && Number.parseFloat(transaction === null || transaction === void 0 ? void 0 : transaction.currency_amount) ? `1 ${transaction.symbol} = ${baseControllers.significantDigits(Number.parseFloat(transaction.currency_amount) / Number.parseFloat(transaction.total_amount))}` : "",
50
- currencyUsed: transaction.selected_currency,
51
- type: transaction.type,
52
- type_name: transaction.type_name,
53
- type_image_link: transaction.type_image_link,
54
- transaction_hash: transaction.transaction_hash,
55
- transaction_category: transaction.transaction_category,
56
- isEtherscan: transaction.isEtherscan,
57
- input: transaction.input || "",
58
- token_id: transaction.token_id || "",
59
- contract_address: transaction.contract_address || "",
60
- nonce: transaction.nonce || "",
61
- is_cancel: !!transaction.is_cancel || false,
62
- gas: transaction.gas || "",
63
- gasPrice: transaction.gasPrice || ""
64
- };
65
- return finalObject;
66
- };
67
20
  /**
68
21
  * Ref - https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt
69
22
  */
@@ -131,83 +84,11 @@ function getChainType(chainId) {
131
84
  }
132
85
  return "custom";
133
86
  }
134
- const addEtherscanTransactions = async params => {
135
- const {
136
- txn,
137
- lowerCaseSelectedAddress,
138
- provider,
139
- chainId,
140
- blockExplorerUrl
141
- } = params;
142
- const transactionPromises = await Promise.all(txn.map(async tx => {
143
- var _SUPPORTED_NETWORKS$c, _SUPPORTED_NETWORKS$c2;
144
- const {
145
- category,
146
- type
147
- } = await TransactionUtils.determineTransactionType(_objectSpread(_objectSpread({}, tx), {}, {
148
- data: tx.input
149
- }), provider);
150
- tx.transaction_category = tx.transaction_category || category;
151
- tx.type_image_link = ((_SUPPORTED_NETWORKS$c = constants.SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c === void 0 ? void 0 : _SUPPORTED_NETWORKS$c.logo) || "";
152
- tx.type_name = (_SUPPORTED_NETWORKS$c2 = constants.SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c2 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c2.ticker;
153
- tx.type = type;
154
- return tx;
155
- }));
156
- const finalTxs = transactionPromises.reduce((accumulator, x) => {
157
- var _SUPPORTED_NETWORKS$c3, _SUPPORTED_NETWORKS$c4;
158
- let totalAmountString = x.value ? new bignumber_js.BigNumber(x.value).div(new bignumber_js.BigNumber(10).pow(new bignumber_js.BigNumber(x.tokenDecimal || 18))).toString() : "";
159
- let type = constants.CONTRACT_TYPE_ETH;
160
- if (x.contractAddress !== "") {
161
- if (x.tokenID) {
162
- type = x.tokenValue ? constants.CONTRACT_TYPE_ERC1155 : constants.CONTRACT_TYPE_ERC721;
163
- } else {
164
- type = constants.CONTRACT_TYPE_ERC20;
165
- }
166
- }
167
- if (type === constants.CONTRACT_TYPE_ERC1155) {
168
- totalAmountString = x.tokenValue;
169
- }
170
- const etherscanTransaction = {
171
- type,
172
- type_image_link: x.type_image_link || "n/a",
173
- type_name: x.tokenName || ((_SUPPORTED_NETWORKS$c3 = constants.SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c3 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c3.ticker) || "n/a",
174
- symbol: x.tokenSymbol || ((_SUPPORTED_NETWORKS$c4 = constants.SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c4 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c4.ticker),
175
- token_id: x.tokenID || "",
176
- total_amount: totalAmountString,
177
- created_at: new Date(Number(x.timeStamp) * 1000),
178
- from: x.from,
179
- to: x.to,
180
- transaction_hash: x.hash,
181
- status: x.txreceipt_status && x.txreceipt_status === "0" ? baseControllers.TransactionStatus.failed : baseControllers.TransactionStatus.confirmed,
182
- isEtherscan: true,
183
- input: x.input,
184
- contract_address: x.contractAddress,
185
- transaction_category: x.transaction_category,
186
- gas: `0x${new bignumber_js.BigNumber(x.gasUsed || 0, 10).toString(16)}`,
187
- gasPrice: `0x${new bignumber_js.BigNumber(x.gasPrice || 0, 10).toString(16)}`,
188
- chain_id: chainId,
189
- currency_amount: "",
190
- nonce: x.nonce,
191
- from_aa_address: "",
192
- is_cancel: false,
193
- selected_currency: ""
194
- };
195
- accumulator.push(formatPastTx({
196
- transaction: etherscanTransaction,
197
- lowerCaseSelectedAddress,
198
- blockExplorerUrl
199
- }));
200
- return accumulator;
201
- }, []);
202
- return finalTxs;
203
- };
204
87
 
205
88
  exports.BNToHex = BNToHex;
206
89
  exports.GAS_LIMITS = GAS_LIMITS;
207
- exports.addEtherscanTransactions = addEtherscanTransactions;
208
90
  exports.bnLessThan = bnLessThan;
209
91
  exports.formatDate = formatDate;
210
- exports.formatPastTx = formatPastTx;
211
92
  exports.formatTime = formatTime;
212
93
  exports.getChainType = getChainType;
213
94
  exports.getEthTxStatus = getEthTxStatus;
@@ -1,7 +1,6 @@
1
1
  import _objectSpread from '@babel/runtime/helpers/objectSpread2';
2
2
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
3
- import { BaseCurrencyController, PollingManager } from '@toruslabs/base-controllers';
4
- import { get } from '@toruslabs/http-helpers';
3
+ import { BaseCurrencyController, PollingManager, resolveAuthHttpClient } from '@toruslabs/base-controllers';
5
4
  import log from 'loglevel';
6
5
 
7
6
  class CurrencyController extends BaseCurrencyController {
@@ -9,13 +8,15 @@ class CurrencyController extends BaseCurrencyController {
9
8
  config,
10
9
  state,
11
10
  idleTimeTracker,
12
- onNetworkChanged
11
+ onNetworkChanged,
12
+ getAuthHttpClient
13
13
  }) {
14
14
  super({
15
15
  config,
16
16
  state
17
17
  });
18
18
  _defineProperty(this, "pollingManager", void 0);
19
+ _defineProperty(this, "getAuthHttpClient", void 0);
19
20
  this.defaultState = _objectSpread(_objectSpread({}, this.defaultState), {}, {
20
21
  commonDenomination: "USD",
21
22
  commonDenominatorPrice: 0
@@ -28,6 +29,7 @@ class CurrencyController extends BaseCurrencyController {
28
29
  this.updateConversionRate();
29
30
  }
30
31
  });
32
+ this.getAuthHttpClient = getAuthHttpClient;
31
33
  this.pollingManager = new PollingManager(idleTimeTracker, this.config.pollInterval);
32
34
  }
33
35
  setCommonDenomination(commonDenomination) {
@@ -84,11 +86,14 @@ class CurrencyController extends BaseCurrencyController {
84
86
  }
85
87
  async retrieveConversionRate(fromCurrency, toCurrency, commonDenomination) {
86
88
  try {
87
- let apiUrl = `${this.config.api}/currency?fsym=${fromCurrency.toUpperCase()}&tsyms=${toCurrency.toUpperCase()}`;
89
+ const httpClient = resolveAuthHttpClient(this.getAuthHttpClient, this.name);
90
+ let apiUrl = `${this.config.api}/v2/currency?fsym=${fromCurrency.toUpperCase()}&tsyms=${toCurrency.toUpperCase()}`;
88
91
  if (commonDenomination && commonDenomination.toUpperCase() !== toCurrency.toUpperCase()) {
89
92
  apiUrl += `,${commonDenomination.toUpperCase()}`;
90
93
  }
91
- const parsedResponse = await get(apiUrl);
94
+ const parsedResponse = await httpClient.get(apiUrl, {
95
+ authenticated: true
96
+ });
92
97
  return parsedResponse;
93
98
  } catch (error) {
94
99
  log.error(error, `CurrencyController - updateCommonDenominatorPrice: Failed to query rate for currency: ${fromCurrency}/ ${toCurrency}`);
@@ -2,33 +2,29 @@ import _defineProperty from '@babel/runtime/helpers/defineProperty';
2
2
  import { BasePreferencesController, CHAIN_NAMESPACES } from '@toruslabs/base-controllers';
3
3
  import { remove0x } from '@toruslabs/metadata-helpers';
4
4
  import log from 'loglevel';
5
- import { MM_TOKEN_API_SUPPORTED_CHAINS, SUPPORTED_NETWORKS } from '../utils/constants.js';
6
- import { addEtherscanTransactions } from '../utils/helpers.js';
5
+ import { SUPPORTED_NETWORKS } from '../utils/constants.js';
7
6
 
8
7
  class PreferencesController extends BasePreferencesController {
9
8
  constructor({
10
9
  config,
11
10
  state,
12
- provider,
13
11
  signAuthMessage,
14
12
  getProviderConfig,
15
13
  setProviderConfig,
16
- validateSignMessage
14
+ validateSignMessage,
15
+ getAuthHttpClient
17
16
  }) {
18
17
  super({
19
18
  config,
20
19
  state,
21
- defaultPreferences: {
22
- etherscanTransactions: []
23
- },
20
+ defaultPreferences: {},
24
21
  signAuthMessage,
25
- validateSignMessage
22
+ validateSignMessage,
23
+ getAuthHttpClient
26
24
  });
27
25
  _defineProperty(this, "chainNamespace", CHAIN_NAMESPACES.EIP155);
28
26
  _defineProperty(this, "getProviderConfig", void 0);
29
27
  _defineProperty(this, "setProviderConfig", void 0);
30
- _defineProperty(this, "provider", void 0);
31
- this.provider = provider;
32
28
  this.getProviderConfig = getProviderConfig;
33
29
  this.setProviderConfig = setProviderConfig;
34
30
  }
@@ -36,15 +32,12 @@ class PreferencesController extends BasePreferencesController {
36
32
  const {
37
33
  address,
38
34
  jwtToken,
39
- calledFromEmbed,
35
+ accessToken,
36
+ origin,
40
37
  userInfo,
41
- rehydrate,
42
38
  type,
43
39
  signatures,
44
- web3AuthClientId,
45
40
  web3AuthNetwork,
46
- loginMode,
47
- sessionPubKey,
48
41
  aaProvider,
49
42
  eoaAddress,
50
43
  mainAddress
@@ -56,6 +49,8 @@ class PreferencesController extends BasePreferencesController {
56
49
  address,
57
50
  userInfo,
58
51
  idToken: jwtToken,
52
+ accessToken,
53
+ origin,
59
54
  type,
60
55
  metadata: {
61
56
  email: userInfo.email,
@@ -67,74 +62,19 @@ class PreferencesController extends BasePreferencesController {
67
62
  main_address: mainAddress
68
63
  }
69
64
  });
70
- const {
71
- groupedAuthConnectionId,
72
- authConnectionId,
73
- userId
74
- } = userInfo || {};
75
65
  if (eoaAddress) this.updateState({
76
66
  eoaAddress
77
67
  }, address);
78
- this.storeUserLogin({
79
- groupedAuthConnectionId,
80
- authConnectionId,
81
- userId,
82
- options: {
83
- calledFromEmbed,
84
- rehydrate
85
- },
86
- address,
87
- web3AuthClientId,
88
- web3AuthNetwork,
89
- sessionPubKey,
90
- loginMode
91
- });
92
68
  }
93
69
  getSelectedAddress() {
94
70
  return this.state.selectedAddress;
95
71
  }
96
- async refetchEtherscanTx(address) {
97
- var _this$getAddressState;
98
- const selectedAddress = address || this.state.selectedAddress;
99
- if (!selectedAddress) return [];
100
- if ((_this$getAddressState = this.getAddressState(selectedAddress)) !== null && _this$getAddressState !== void 0 && _this$getAddressState.jwtToken) {
101
- const {
102
- chainId
103
- } = this.getProviderConfig();
104
- if (MM_TOKEN_API_SUPPORTED_CHAINS.includes(chainId)) {
105
- const lowerCaseSelectedAddress = selectedAddress.toLowerCase();
106
- const etherscanTxn = await this.fetchEtherscanTx({
107
- selectedAddress,
108
- chainId: this.getProviderConfig().chainId
109
- });
110
- const finalEthScanTxn = await addEtherscanTransactions({
111
- txn: etherscanTxn,
112
- lowerCaseSelectedAddress,
113
- provider: this.provider,
114
- chainId,
115
- blockExplorerUrl: this.getBlockExplorerUrl()
116
- });
117
- log.info("Formatted Etherscan Response", finalEthScanTxn);
118
- this.updateState({
119
- etherscanTransactions: finalEthScanTxn
120
- });
121
- return etherscanTxn;
122
- }
123
- }
124
- }
125
- async fetchEtherscanTx(parameters) {
126
- try {
127
- const response = await this.wsApiClient.authGet(`etherscan?chainId=${parameters.chainId}`, this.authCredentials(parameters.selectedAddress));
128
- log.info("Etherscan Response API", response);
129
- return response.success ? response.data : [];
130
- } catch (error) {
131
- log.error("unable to fetch etherscan tx", error);
132
- return [];
133
- }
134
- }
135
72
  async fetchQuote(parameters) {
136
73
  try {
137
- const response = await this.wsApiClient.authPost("quote", parameters, this.authCredentials());
74
+ const response = await this.getAuthHttpClient().post(`${this.config.api}/v2/quote`, parameters, {
75
+ authenticated: true,
76
+ headers: this.constructAuthHeaders()
77
+ });
138
78
  return response.success ? response.data : [];
139
79
  } catch (error) {
140
80
  log.error("unable to get swap quote", error);
@@ -143,29 +83,36 @@ class PreferencesController extends BasePreferencesController {
143
83
  }
144
84
  async getEtherScanTokens(address, chainId, skipCache) {
145
85
  const selectedAddress = address;
146
- let path = `tokens?chainId=${chainId}&address=${selectedAddress}`;
86
+ let path = `v2/tokens?chainId=${chainId}&address=${selectedAddress}`;
147
87
  if (skipCache) {
148
88
  path += `&skipCache=true`;
149
89
  }
150
- const result = await this.wsApiClient.authGet(path, this.authCredentials());
90
+ // TODO: pass selected address as headers and not as a query parameter
91
+ const result = await this.getAuthHttpClient().get(`${this.config.api}/${path}`, {
92
+ authenticated: true
93
+ });
151
94
  return result.data;
152
95
  }
153
96
  async getSimpleHashNfts(address, chainId, skipCache) {
154
97
  const selectedAddress = address;
155
- let path = `nfts?chainId=${chainId}&address=${selectedAddress}`;
98
+ let path = `v2/nfts?chainId=${chainId}&address=${selectedAddress}`;
156
99
  if (skipCache) {
157
100
  path += `&skipCache=true`;
158
101
  }
159
- const result = await this.wsApiClient.authGet(path, this.authCredentials());
102
+ // TODO: pass selected address as headers and not as a query parameter
103
+ const result = await this.getAuthHttpClient().get(`${this.config.api}/${path}`, {
104
+ authenticated: true,
105
+ headers: this.constructAuthHeaders()
106
+ });
160
107
  return result.data;
161
108
  }
162
109
  getCustomTokens(address) {
163
- var _this$getAddressState2, _this$getAddressState3;
164
- return (_this$getAddressState2 = (_this$getAddressState3 = this.getAddressState(address)) === null || _this$getAddressState3 === void 0 ? void 0 : _this$getAddressState3.customTokens) !== null && _this$getAddressState2 !== void 0 ? _this$getAddressState2 : [];
110
+ var _this$getAddressState, _this$getAddressState2;
111
+ return (_this$getAddressState = (_this$getAddressState2 = this.getAddressState(address)) === null || _this$getAddressState2 === void 0 ? void 0 : _this$getAddressState2.customTokens) !== null && _this$getAddressState !== void 0 ? _this$getAddressState : [];
165
112
  }
166
113
  getCustomNfts(address) {
167
- var _this$getAddressState4, _this$getAddressState5;
168
- return (_this$getAddressState4 = (_this$getAddressState5 = this.getAddressState(address)) === null || _this$getAddressState5 === void 0 ? void 0 : _this$getAddressState5.customNfts) !== null && _this$getAddressState4 !== void 0 ? _this$getAddressState4 : [];
114
+ var _this$getAddressState3, _this$getAddressState4;
115
+ return (_this$getAddressState3 = (_this$getAddressState4 = this.getAddressState(address)) === null || _this$getAddressState4 === void 0 ? void 0 : _this$getAddressState4.customNfts) !== null && _this$getAddressState3 !== void 0 ? _this$getAddressState3 : [];
169
116
  }
170
117
 
171
118
  // NOTE: keep address params for now, might need to handle aa addresses later
@@ -192,12 +139,6 @@ class PreferencesController extends BasePreferencesController {
192
139
  getChainOptions() {
193
140
  return Object.values(SUPPORTED_NETWORKS);
194
141
  }
195
- getBlockExplorerUrl() {
196
- const supportedNetworks = this.getChainOptions();
197
- const network = supportedNetworks.find(x => x.chainId === this.getProviderConfig().chainId);
198
- if (!network) return "";
199
- return `${network.blockExplorerUrl}`;
200
- }
201
142
  }
202
143
 
203
144
  export { PreferencesController };
@@ -1,7 +1,6 @@
1
1
  import _objectSpread from '@babel/runtime/helpers/objectSpread2';
2
2
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
3
- import { BaseController, PollingManager } from '@toruslabs/base-controllers';
4
- import { get } from '@toruslabs/http-helpers';
3
+ import { BaseController, PollingManager, resolveAuthHttpClient } from '@toruslabs/base-controllers';
5
4
  import log from 'loglevel';
6
5
  import { COINGECKO_PLATFORMS_CHAIN_CODE_MAP, COINGECKO_SUPPORTED_CURRENCIES } from '../utils/constants.js';
7
6
 
@@ -16,13 +15,15 @@ class TokenRatesController extends BaseController {
16
15
  idleTimeTracker,
17
16
  onPreferencesStateChange,
18
17
  onNetworkStateChange,
19
- onTokensStateChange
18
+ onTokensStateChange,
19
+ getAuthHttpClient
20
20
  }) {
21
21
  super({
22
22
  config,
23
23
  state
24
24
  });
25
25
  _defineProperty(this, "pollingManager", void 0);
26
+ _defineProperty(this, "getAuthHttpClient", void 0);
26
27
  this.defaultState = _objectSpread(_objectSpread({}, this.defaultState), {}, {
27
28
  contractExchangeRates: {}
28
29
  });
@@ -50,18 +51,19 @@ class TokenRatesController extends BaseController {
50
51
  tokens
51
52
  } = tokensState;
52
53
  const currentUserTokens = tokens[this.config.selectedAddress];
53
- if ((currentUserTokens === null || currentUserTokens === void 0 ? void 0 : currentUserTokens.length) > 0 && this.config.tokens !== tokens[this.config.selectedAddress]) {
54
+ if ((currentUserTokens === null || currentUserTokens === void 0 ? void 0 : currentUserTokens.length) > 0 && this.config.tokens !== currentUserTokens) {
54
55
  this.configure({
55
- tokens: tokens[this.config.selectedAddress]
56
+ tokens: currentUserTokens
56
57
  });
57
58
  this.updateExchangeRates();
58
59
  }
59
60
  });
61
+ this.getAuthHttpClient = getAuthHttpClient;
60
62
  this.pollingManager = new PollingManager(idleTimeTracker, this.config.pollInterval);
61
63
  }
62
64
 
63
65
  /**
64
- * Creates a new poll, using setInterval, to periodically call updateConversionRate. The id of the interval is
66
+ * Creates a new poll, using setInterval, to periodically call updateExchangeRates. The id of the interval is
65
67
  * stored at the controller's conversionInterval property. If it is called and such an id already exists, the
66
68
  * previous interval is clear and a new one is created.
67
69
  */
@@ -84,17 +86,24 @@ class TokenRatesController extends BaseController {
84
86
  });
85
87
  }
86
88
  async fetchExchangeRates(nativeCurrency, chainCodes) {
89
+ const httpClient = resolveAuthHttpClient(this.getAuthHttpClient, this.name);
87
90
  const contractAddresses = this.config.tokens.map(token => token.tokenAddress);
88
91
  const isNativeCurrencySupported = COINGECKO_SUPPORTED_CURRENCIES.has(nativeCurrency.toLowerCase());
89
92
  if (isNativeCurrencySupported) {
90
- const response = await get(`${this.config.currencyApi}/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${nativeCurrency.toLowerCase()}`);
93
+ const response = await httpClient.get(`${this.config.currencyApi}/v2/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${nativeCurrency.toLowerCase()}`, {
94
+ authenticated: true
95
+ });
91
96
  const newContractExchangeRates = {};
92
97
  Object.keys(response).forEach(contractAddress => {
93
98
  newContractExchangeRates[contractAddress] = response[contractAddress][nativeCurrency.toLowerCase()] || 0;
94
99
  });
95
100
  return newContractExchangeRates;
96
101
  }
97
- const [response, currencyResponse] = await Promise.all([get(`${this.config.currencyApi}/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${DEFAULT_CURRENCY}`), get(`${this.config.currencyApi}/currency?fsym=${nativeCurrency.toUpperCase()}&tsyms=${DEFAULT_CURRENCY.toUpperCase()}`)]);
102
+ const [response, currencyResponse] = await Promise.all([httpClient.get(`${this.config.currencyApi}/v2/currency/exchange-rates?platform=${chainCodes.platform}&contract_addresses=${contractAddresses.join(",")}&vs_currencies=${DEFAULT_CURRENCY}`, {
103
+ authenticated: true
104
+ }), httpClient.get(`${this.config.currencyApi}/v2/currency?fsym=${nativeCurrency.toUpperCase()}&tsyms=${DEFAULT_CURRENCY.toUpperCase()}`, {
105
+ authenticated: true
106
+ })]);
98
107
  const newContractExchangeRates = {};
99
108
  Object.keys(response).forEach(contractAddress => {
100
109
  newContractExchangeRates[contractAddress] = response[contractAddress][DEFAULT_CURRENCY] * Number.parseFloat(currencyResponse[DEFAULT_CURRENCY]) || 0;
@@ -29,7 +29,7 @@ export { ARBITRUM_MAINNET_CHAIN_ID, ARBITRUM_TESTNET_CHAIN_ID, AVALANCHE_MAINNET
29
29
  export { addCurrencies, conversionGTE, conversionGreaterThan, conversionLTE, conversionLessThan, conversionMax, conversionUtil, decGWEIToHexWEI, getBigNumber, hexWEIToDecGWEI, multiplyCurrencies, subtractCurrencies, toNegative } from './utils/conversionUtils.js';
30
30
  export { EIP5792ErrorCode, EIP_5792_METHODS, Eip5792AtomicStatus, GetCallsStatusCode } from './utils/eip5792Types.js';
31
31
  export { DUMMY_AUTHORIZATION_SIGNATURE, EIP_7702_METHODS, EIP_7702_PREFIX, EIP_7702_REVOKE_ADDRESS } from './utils/eip7702Types.js';
32
- export { BNToHex, GAS_LIMITS, addEtherscanTransactions, bnLessThan, formatDate, formatPastTx, formatTime, getChainType, getEthTxStatus, getEtherScanHashLink, getIpfsEndpoint, hexToBn, isAddressByChainId, sanitizeNftMetdataUrl, toChecksumAddressByChainId } from './utils/helpers.js';
32
+ export { BNToHex, GAS_LIMITS, bnLessThan, formatDate, formatTime, getChainType, getEthTxStatus, getEtherScanHashLink, getIpfsEndpoint, hexToBn, isAddressByChainId, sanitizeNftMetdataUrl, toChecksumAddressByChainId } from './utils/helpers.js';
33
33
  export { TRANSACTION_CATEGORY_EIP7702 } from './utils/interfaces.js';
34
34
  export { BiconomySmartAccount } from './AccountAbstraction/smartAccounts/BiconomySmartAccount.js';
35
35
  export { CacheStrategy, blockTagParamIndex, cacheIdentifierForRequest, cacheTypeForMethod } from './Network/cacheIdentifier.js';
@@ -1,11 +1,9 @@
1
- import _objectSpread from '@babel/runtime/helpers/objectSpread2';
2
- import { TransactionStatus, formatSmallNumbers, significantDigits, ACTIVITY_ACTION_RECEIVE, ACTIVITY_ACTION_SEND, addressSlicer } from '@toruslabs/base-controllers';
1
+ import { TransactionStatus } from '@toruslabs/base-controllers';
3
2
  import { add0x, remove0x } from '@toruslabs/metadata-helpers';
4
3
  import { BigNumber } from 'bignumber.js';
5
4
  import log from 'loglevel';
6
5
  import { toHex, isAddress, getAddress } from 'viem';
7
- import { determineTransactionType } from '../Transaction/TransactionUtils.js';
8
- import { SUPPORTED_NETWORKS, CONTRACT_TYPE_ERC1155, CONTRACT_TYPE_ERC721, CONTRACT_TYPE_ERC20, MAINNET_CHAIN_ID, TEST_CHAINS, METHOD_TYPES, CONTRACT_TYPE_ETH } from './constants.js';
6
+ import { MAINNET_CHAIN_ID, TEST_CHAINS, METHOD_TYPES, SUPPORTED_NETWORKS } from './constants.js';
9
7
 
10
8
  function hexToBn(hex) {
11
9
  return new BigNumber(remove0x(hex), 16);
@@ -17,51 +15,6 @@ function getEtherScanHashLink(txHash, chainId) {
17
15
  if (!SUPPORTED_NETWORKS[chainId]) return "";
18
16
  return `${SUPPORTED_NETWORKS[chainId].blockExplorerUrl}/tx/${txHash}`;
19
17
  }
20
- const formatPastTx = params => {
21
- var _transaction$to;
22
- const {
23
- transaction,
24
- lowerCaseSelectedAddress,
25
- blockExplorerUrl
26
- } = params;
27
- let totalAmountString = "";
28
- if (transaction.type === CONTRACT_TYPE_ERC721 || transaction.type === CONTRACT_TYPE_ERC1155) totalAmountString = transaction.symbol;else if (transaction.type === CONTRACT_TYPE_ERC20) totalAmountString = formatSmallNumbers(Number.parseFloat(transaction.total_amount), transaction.symbol, true);else totalAmountString = formatSmallNumbers(Number.parseFloat(transaction.total_amount), transaction.type_name, true);
29
- const currencyAmountString = transaction.type === CONTRACT_TYPE_ERC721 || transaction.type === CONTRACT_TYPE_ERC1155 || transaction.isEtherscan ? "" : formatSmallNumbers(Number.parseFloat(transaction.currency_amount), transaction.selected_currency, true);
30
- const finalObject = {
31
- id: transaction.created_at.toString(),
32
- date: new Date(transaction.created_at).toString(),
33
- from: transaction.from,
34
- from_aa_address: transaction.from_aa_address,
35
- slicedFrom: typeof transaction.from === "string" ? addressSlicer(transaction.from) : "",
36
- to: transaction.to,
37
- slicedTo: typeof transaction.to === "string" ? addressSlicer(transaction.to) : "",
38
- action: lowerCaseSelectedAddress === ((_transaction$to = transaction.to) === null || _transaction$to === void 0 ? void 0 : _transaction$to.toLowerCase()) || "" ? ACTIVITY_ACTION_RECEIVE : ACTIVITY_ACTION_SEND,
39
- totalAmount: transaction.total_amount,
40
- totalAmountString,
41
- currencyAmount: transaction.currency_amount,
42
- currencyAmountString,
43
- amount: `${totalAmountString} / ${currencyAmountString}`,
44
- status: transaction.status,
45
- etherscanLink: blockExplorerUrl ? `${blockExplorerUrl}/tx/${transaction.transaction_hash}` : "",
46
- chainId: transaction.chain_id,
47
- ethRate: Number.parseFloat(transaction === null || transaction === void 0 ? void 0 : transaction.total_amount) && Number.parseFloat(transaction === null || transaction === void 0 ? void 0 : transaction.currency_amount) ? `1 ${transaction.symbol} = ${significantDigits(Number.parseFloat(transaction.currency_amount) / Number.parseFloat(transaction.total_amount))}` : "",
48
- currencyUsed: transaction.selected_currency,
49
- type: transaction.type,
50
- type_name: transaction.type_name,
51
- type_image_link: transaction.type_image_link,
52
- transaction_hash: transaction.transaction_hash,
53
- transaction_category: transaction.transaction_category,
54
- isEtherscan: transaction.isEtherscan,
55
- input: transaction.input || "",
56
- token_id: transaction.token_id || "",
57
- contract_address: transaction.contract_address || "",
58
- nonce: transaction.nonce || "",
59
- is_cancel: !!transaction.is_cancel || false,
60
- gas: transaction.gas || "",
61
- gasPrice: transaction.gasPrice || ""
62
- };
63
- return finalObject;
64
- };
65
18
 
66
19
  /**
67
20
  * Ref - https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt
@@ -130,75 +83,5 @@ function getChainType(chainId) {
130
83
  }
131
84
  return "custom";
132
85
  }
133
- const addEtherscanTransactions = async params => {
134
- const {
135
- txn,
136
- lowerCaseSelectedAddress,
137
- provider,
138
- chainId,
139
- blockExplorerUrl
140
- } = params;
141
- const transactionPromises = await Promise.all(txn.map(async tx => {
142
- var _SUPPORTED_NETWORKS$c, _SUPPORTED_NETWORKS$c2;
143
- const {
144
- category,
145
- type
146
- } = await determineTransactionType(_objectSpread(_objectSpread({}, tx), {}, {
147
- data: tx.input
148
- }), provider);
149
- tx.transaction_category = tx.transaction_category || category;
150
- tx.type_image_link = ((_SUPPORTED_NETWORKS$c = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c === void 0 ? void 0 : _SUPPORTED_NETWORKS$c.logo) || "";
151
- tx.type_name = (_SUPPORTED_NETWORKS$c2 = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c2 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c2.ticker;
152
- tx.type = type;
153
- return tx;
154
- }));
155
- const finalTxs = transactionPromises.reduce((accumulator, x) => {
156
- var _SUPPORTED_NETWORKS$c3, _SUPPORTED_NETWORKS$c4;
157
- let totalAmountString = x.value ? new BigNumber(x.value).div(new BigNumber(10).pow(new BigNumber(x.tokenDecimal || 18))).toString() : "";
158
- let type = CONTRACT_TYPE_ETH;
159
- if (x.contractAddress !== "") {
160
- if (x.tokenID) {
161
- type = x.tokenValue ? CONTRACT_TYPE_ERC1155 : CONTRACT_TYPE_ERC721;
162
- } else {
163
- type = CONTRACT_TYPE_ERC20;
164
- }
165
- }
166
- if (type === CONTRACT_TYPE_ERC1155) {
167
- totalAmountString = x.tokenValue;
168
- }
169
- const etherscanTransaction = {
170
- type,
171
- type_image_link: x.type_image_link || "n/a",
172
- type_name: x.tokenName || ((_SUPPORTED_NETWORKS$c3 = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c3 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c3.ticker) || "n/a",
173
- symbol: x.tokenSymbol || ((_SUPPORTED_NETWORKS$c4 = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c4 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c4.ticker),
174
- token_id: x.tokenID || "",
175
- total_amount: totalAmountString,
176
- created_at: new Date(Number(x.timeStamp) * 1000),
177
- from: x.from,
178
- to: x.to,
179
- transaction_hash: x.hash,
180
- status: x.txreceipt_status && x.txreceipt_status === "0" ? TransactionStatus.failed : TransactionStatus.confirmed,
181
- isEtherscan: true,
182
- input: x.input,
183
- contract_address: x.contractAddress,
184
- transaction_category: x.transaction_category,
185
- gas: `0x${new BigNumber(x.gasUsed || 0, 10).toString(16)}`,
186
- gasPrice: `0x${new BigNumber(x.gasPrice || 0, 10).toString(16)}`,
187
- chain_id: chainId,
188
- currency_amount: "",
189
- nonce: x.nonce,
190
- from_aa_address: "",
191
- is_cancel: false,
192
- selected_currency: ""
193
- };
194
- accumulator.push(formatPastTx({
195
- transaction: etherscanTransaction,
196
- lowerCaseSelectedAddress,
197
- blockExplorerUrl
198
- }));
199
- return accumulator;
200
- }, []);
201
- return finalTxs;
202
- };
203
86
 
204
- export { BNToHex, GAS_LIMITS, addEtherscanTransactions, bnLessThan, formatDate, formatPastTx, formatTime, getChainType, getEthTxStatus, getEtherScanHashLink, getIpfsEndpoint, hexToBn, isAddressByChainId, sanitizeNftMetdataUrl, toChecksumAddressByChainId };
87
+ export { BNToHex, GAS_LIMITS, bnLessThan, formatDate, formatTime, getChainType, getEthTxStatus, getEtherScanHashLink, getIpfsEndpoint, hexToBn, isAddressByChainId, sanitizeNftMetdataUrl, toChecksumAddressByChainId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toruslabs/ethereum-controllers",
3
- "version": "9.3.0",
3
+ "version": "9.4.0",
4
4
  "homepage": "https://github.com/torusresearch/controllers#readme",
5
5
  "license": "ISC",
6
6
  "sideEffects": false,
@@ -21,10 +21,10 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@metamask/smart-accounts-kit": "~0.4.0-beta.1",
24
- "@toruslabs/base-controllers": "^9.3.0",
24
+ "@toruslabs/base-controllers": "^9.4.0",
25
25
  "@toruslabs/http-helpers": "^9.0.0",
26
26
  "@toruslabs/metadata-helpers": "^8.2.0",
27
- "@web3auth/auth": "^11.3.0",
27
+ "@web3auth/auth": "^11.4.0",
28
28
  "async-mutex": "^0.5.0",
29
29
  "bignumber.js": "^9.3.1",
30
30
  "deepmerge": "^4.3.1",
@@ -64,7 +64,7 @@
64
64
  "publishConfig": {
65
65
  "access": "public"
66
66
  },
67
- "gitHead": "ba77c9c4235c3f78bac84da49d0931463c056c2d",
67
+ "gitHead": "b84f5368b4ba5c51f6ab94c4f2b951a2b53c808c",
68
68
  "devDependencies": {
69
69
  "@types/uuid": "^11.0.0",
70
70
  "typechain": "^8.3.2"