@rango-dev/widget-embedded 0.37.0 → 0.37.1-next.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.
Files changed (157) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/QueueManager.d.ts.map +1 -1
  3. package/dist/components/ConfirmWalletsModal/ConfirmWalletsModal.d.ts.map +1 -1
  4. package/dist/components/ConfirmWalletsModal/WalletList.d.ts.map +1 -1
  5. package/dist/components/Layout/Layout.d.ts.map +1 -1
  6. package/dist/components/Quote/Quote.d.ts.map +1 -1
  7. package/dist/components/Quote/Quote.styles.d.ts +1 -1
  8. package/dist/components/Quote/Quote.types.d.ts +2 -0
  9. package/dist/components/Quote/Quote.types.d.ts.map +1 -1
  10. package/dist/components/Quote/QuoteCostDetails.d.ts.map +1 -1
  11. package/dist/components/Quote/QuoteCostDetails.styles.d.ts.map +1 -1
  12. package/dist/components/QuoteWarningsAndErrors/QuoteWarningsAndErrors.helpers.d.ts.map +1 -1
  13. package/dist/components/Quotes/Quotes.d.ts.map +1 -1
  14. package/dist/components/RefreshModal/RefreshModal.styles.d.ts +1 -1
  15. package/dist/components/SwapDetails/SwapDetails.d.ts.map +1 -1
  16. package/dist/components/SwapDetailsAlerts/SwapDetailsAlerts.types.d.ts +1 -1
  17. package/dist/components/SwapDetailsAlerts/SwapDetailsAlerts.types.d.ts.map +1 -1
  18. package/dist/components/SwapDetailsModal/SwapDetailsCompleteModal.d.ts.map +1 -1
  19. package/dist/components/TokenList/TokenList.d.ts.map +1 -1
  20. package/dist/components/WalletStatefulConnect/DerivationPath.helpers.d.ts +2 -1
  21. package/dist/components/WalletStatefulConnect/DerivationPath.helpers.d.ts.map +1 -1
  22. package/dist/components/WalletStatefulConnect/Namespaces.d.ts.map +1 -1
  23. package/dist/components/WalletStatefulConnect/Namespaces.types.d.ts +1 -1
  24. package/dist/components/WalletStatefulConnect/Namespaces.types.d.ts.map +1 -1
  25. package/dist/constants/quote.d.ts +10 -0
  26. package/dist/constants/quote.d.ts.map +1 -1
  27. package/dist/containers/ExpandedQuotes/ExpandedQuotes.styles.d.ts.map +1 -1
  28. package/dist/containers/Inputs/Inputs.d.ts.map +1 -1
  29. package/dist/containers/QuoteInfo/QuoteInfo.d.ts.map +1 -1
  30. package/dist/containers/Wallets/Wallets.d.ts.map +1 -1
  31. package/dist/containers/WidgetInfo/WidgetInfo.d.ts.map +1 -1
  32. package/dist/containers/WidgetInfo/WidgetInfo.helpers.d.ts +1 -1
  33. package/dist/containers/WidgetInfo/WidgetInfo.types.d.ts +2 -2
  34. package/dist/containers/WidgetInfo/WidgetInfo.types.d.ts.map +1 -1
  35. package/dist/hooks/useConfirmSwap/useConfirmSwap.d.ts.map +1 -1
  36. package/dist/hooks/useConfirmSwap/useConfirmSwap.helpers.d.ts +6 -4
  37. package/dist/hooks/useConfirmSwap/useConfirmSwap.helpers.d.ts.map +1 -1
  38. package/dist/hooks/useFetchApiConfig.d.ts.map +1 -1
  39. package/dist/hooks/useFetchCustomToken.d.ts.map +1 -1
  40. package/dist/hooks/useStatefulConnect/useStatefulConnect.d.ts +2 -1
  41. package/dist/hooks/useStatefulConnect/useStatefulConnect.d.ts.map +1 -1
  42. package/dist/hooks/useStatefulConnect/useStatefulConnect.types.d.ts +3 -5
  43. package/dist/hooks/useStatefulConnect/useStatefulConnect.types.d.ts.map +1 -1
  44. package/dist/hooks/useSubscribeToWidgetEvents/useSubscribeToWidgetEvents.d.ts.map +1 -1
  45. package/dist/hooks/useSwapInput.d.ts.map +1 -1
  46. package/dist/hooks/useWalletList.d.ts.map +1 -1
  47. package/dist/hooks/useWalletProviders/useWalletProviders.d.ts +2 -3
  48. package/dist/hooks/useWalletProviders/useWalletProviders.d.ts.map +1 -1
  49. package/dist/index.d.ts +1 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +2 -2
  52. package/dist/index.js.map +4 -4
  53. package/dist/pages/ConfirmSwapPage.d.ts.map +1 -1
  54. package/dist/pages/Home.d.ts.map +1 -1
  55. package/dist/pages/SelectSwapItemsPage.d.ts.map +1 -1
  56. package/dist/store/app.d.ts +2 -4
  57. package/dist/store/app.d.ts.map +1 -1
  58. package/dist/store/quote.d.ts.map +1 -1
  59. package/dist/store/slices/config.d.ts +4 -0
  60. package/dist/store/slices/config.d.ts.map +1 -1
  61. package/dist/store/slices/data.d.ts.map +1 -1
  62. package/dist/store/slices/types.d.ts +6 -0
  63. package/dist/store/slices/types.d.ts.map +1 -0
  64. package/dist/store/slices/wallets.d.ts +60 -0
  65. package/dist/store/slices/wallets.d.ts.map +1 -0
  66. package/dist/store/ui.d.ts +4 -0
  67. package/dist/store/ui.d.ts.map +1 -1
  68. package/dist/store/utils/wallets.d.ts +17 -0
  69. package/dist/store/utils/wallets.d.ts.map +1 -0
  70. package/dist/types/config.d.ts +6 -3
  71. package/dist/types/config.d.ts.map +1 -1
  72. package/dist/types/quote.d.ts +8 -17
  73. package/dist/types/quote.d.ts.map +1 -1
  74. package/dist/types/wallets.d.ts +3 -7
  75. package/dist/types/wallets.d.ts.map +1 -1
  76. package/dist/utils/providers.d.ts +8 -9
  77. package/dist/utils/providers.d.ts.map +1 -1
  78. package/dist/utils/quote.d.ts +5 -6
  79. package/dist/utils/quote.d.ts.map +1 -1
  80. package/dist/utils/settings.d.ts +1 -0
  81. package/dist/utils/settings.d.ts.map +1 -1
  82. package/dist/utils/swap.d.ts +5 -5
  83. package/dist/utils/swap.d.ts.map +1 -1
  84. package/dist/utils/wallets.d.ts +12 -14
  85. package/dist/utils/wallets.d.ts.map +1 -1
  86. package/dist/widget-embedded.build.json +1 -1
  87. package/package.json +8 -8
  88. package/src/QueueManager.tsx +17 -11
  89. package/src/components/ConfirmWalletsModal/ConfirmWalletsModal.tsx +5 -24
  90. package/src/components/ConfirmWalletsModal/WalletList.tsx +10 -7
  91. package/src/components/Layout/Layout.tsx +1 -3
  92. package/src/components/Quote/Quote.tsx +22 -3
  93. package/src/components/Quote/Quote.types.ts +2 -0
  94. package/src/components/Quote/QuoteCostDetails.styles.ts +0 -1
  95. package/src/components/Quote/QuoteCostDetails.tsx +23 -4
  96. package/src/components/QuoteWarningsAndErrors/QuoteWarningsAndErrors.helpers.ts +42 -22
  97. package/src/components/Quotes/Quotes.tsx +2 -3
  98. package/src/components/StatefulConnectModal/StatefulConnectModal.tsx +1 -1
  99. package/src/components/SwapDetails/SwapDetails.tsx +14 -6
  100. package/src/components/SwapDetailsAlerts/SwapDetailsAlerts.types.ts +1 -1
  101. package/src/components/SwapDetailsModal/SwapDetailsCompleteModal.tsx +26 -13
  102. package/src/components/TokenList/TokenList.tsx +4 -27
  103. package/src/components/WalletStatefulConnect/DerivationPath.helpers.ts +2 -1
  104. package/src/components/WalletStatefulConnect/Namespaces.tsx +31 -38
  105. package/src/components/WalletStatefulConnect/Namespaces.types.tsx +1 -1
  106. package/src/constants/quote.ts +25 -0
  107. package/src/containers/ExpandedQuotes/ExpandedQuotes.styles.ts +1 -0
  108. package/src/containers/ExpandedQuotes/ExpandedQuotes.tsx +1 -1
  109. package/src/containers/Inputs/Inputs.tsx +20 -7
  110. package/src/containers/QuoteInfo/QuoteInfo.tsx +3 -9
  111. package/src/containers/Wallets/Wallets.tsx +82 -16
  112. package/src/containers/WidgetInfo/WidgetInfo.helpers.ts +2 -2
  113. package/src/containers/WidgetInfo/WidgetInfo.tsx +10 -8
  114. package/src/containers/WidgetInfo/WidgetInfo.types.ts +2 -2
  115. package/src/hooks/useConfirmSwap/useConfirmSwap.helpers.ts +29 -66
  116. package/src/hooks/useConfirmSwap/useConfirmSwap.ts +10 -15
  117. package/src/hooks/useFetchApiConfig.ts +5 -1
  118. package/src/hooks/useFetchCustomToken.ts +5 -0
  119. package/src/hooks/useStatefulConnect/useStatefulConnect.ts +50 -17
  120. package/src/hooks/useStatefulConnect/useStatefulConnect.types.ts +3 -5
  121. package/src/hooks/useSubscribeToWidgetEvents/useSubscribeToWidgetEvents.ts +7 -6
  122. package/src/hooks/useSwapInput.ts +3 -11
  123. package/src/hooks/useWalletList.ts +6 -8
  124. package/src/hooks/useWalletProviders/useWalletProviders.ts +8 -12
  125. package/src/index.ts +1 -1
  126. package/src/pages/ConfirmSwapPage.tsx +7 -15
  127. package/src/pages/Home.tsx +5 -3
  128. package/src/pages/SelectSwapItemsPage.tsx +1 -2
  129. package/src/store/app.ts +4 -4
  130. package/src/store/quote.ts +3 -13
  131. package/src/store/slices/config.ts +76 -0
  132. package/src/store/slices/data.test.ts +23 -1
  133. package/src/store/slices/data.ts +3 -2
  134. package/src/store/slices/types.ts +9 -0
  135. package/src/store/slices/wallets.ts +488 -0
  136. package/src/store/ui.ts +6 -0
  137. package/src/store/utils/wallets.ts +108 -0
  138. package/src/types/config.ts +7 -3
  139. package/src/types/quote.ts +10 -24
  140. package/src/types/wallets.ts +3 -7
  141. package/src/utils/providers.ts +88 -36
  142. package/src/utils/quote.ts +57 -45
  143. package/src/utils/settings.ts +4 -0
  144. package/src/utils/swap.ts +56 -37
  145. package/src/utils/wallets.ts +76 -141
  146. package/dist/constants/warnings.d.ts +0 -3
  147. package/dist/constants/warnings.d.ts.map +0 -1
  148. package/dist/hooks/useObserveBalanceChanges/index.d.ts +0 -2
  149. package/dist/hooks/useObserveBalanceChanges/index.d.ts.map +0 -1
  150. package/dist/hooks/useObserveBalanceChanges/useObserveBalanceChanges.d.ts +0 -4
  151. package/dist/hooks/useObserveBalanceChanges/useObserveBalanceChanges.d.ts.map +0 -1
  152. package/dist/store/wallets.d.ts +0 -66
  153. package/dist/store/wallets.d.ts.map +0 -1
  154. package/src/constants/warnings.ts +0 -26
  155. package/src/hooks/useObserveBalanceChanges/index.ts +0 -1
  156. package/src/hooks/useObserveBalanceChanges/useObserveBalanceChanges.ts +0 -68
  157. package/src/store/wallets.ts +0 -268
@@ -21,11 +21,7 @@ import {
21
21
  WidgetEvents,
22
22
  } from '../types';
23
23
  import { isPositiveNumber } from '../utils/numbers';
24
- import {
25
- getQuoteFromTokenUsdPrice,
26
- getQuoteToTokenUsdPrice,
27
- } from '../utils/quote';
28
- import { calcOutputUsdValue } from '../utils/swap';
24
+ import { getUsdInputFrom, getUsdOutputFrom } from '../utils/swap';
29
25
 
30
26
  import createSelectors from './selectors';
31
27
 
@@ -137,14 +133,8 @@ export const useQuoteStore = createSelectors(
137
133
  outputAmount = !!quote?.outputAmount
138
134
  ? new BigNumber(quote?.outputAmount)
139
135
  : null;
140
- inputUsdValue = calcOutputUsdValue(
141
- state.inputAmount,
142
- getQuoteFromTokenUsdPrice(quote) || state.fromToken?.usdPrice
143
- );
144
- outputUsdValue = calcOutputUsdValue(
145
- quote.outputAmount,
146
- getQuoteToTokenUsdPrice(quote) || state.toToken?.usdPrice
147
- );
136
+ inputUsdValue = getUsdInputFrom(quote) ?? ZERO;
137
+ outputUsdValue = getUsdOutputFrom(quote) ?? ZERO;
148
138
  }
149
139
  return {
150
140
  selectedQuote: quote,
@@ -3,9 +3,31 @@ import type { SettingsSlice } from './settings';
3
3
  import type { WidgetConfig } from '../../types';
4
4
  import type { StateCreatorWithInitialData } from '../app';
5
5
 
6
+ import { allProviders as getAllProviders } from '@rango-dev/provider-all';
7
+ import { type VersionedProviders } from '@rango-dev/wallets-core';
8
+
6
9
  import { cacheService } from '../../services/cacheService';
10
+ import {
11
+ matchAndGenerateProviders,
12
+ type ProvidersOptions,
13
+ } from '../../utils/providers';
7
14
  import { matchTokensFromConfigWithMeta } from '../utils';
8
15
 
16
+ function makeProvidersOptionsFromConfig(
17
+ config: WidgetConfig
18
+ ): ProvidersOptions {
19
+ const options: ProvidersOptions = {
20
+ walletConnectProjectId: config?.walletConnectProjectId,
21
+ trezorManifest: config?.trezorManifest,
22
+ tonConnect: config?.tonConnect,
23
+ walletConnectListedDesktopWalletLink:
24
+ config.__UNSTABLE_OR_INTERNAL__?.walletConnectListedDesktopWalletLink,
25
+ experimentalWallet: config.features?.experimentalWallet,
26
+ };
27
+
28
+ return options;
29
+ }
30
+
9
31
  export const DEFAULT_CONFIG: WidgetConfig = {
10
32
  apiKey: '',
11
33
  title: undefined,
@@ -21,6 +43,9 @@ export const DEFAULT_CONFIG: WidgetConfig = {
21
43
  manifestUrl:
22
44
  'https://raw.githubusercontent.com/rango-exchange/rango-types/main/assets/manifests/tonconnect-manifest.json',
23
45
  },
46
+ features: {
47
+ experimentalWallet: 'enabled',
48
+ },
24
49
  };
25
50
 
26
51
  interface IframeConfigs {
@@ -58,6 +83,31 @@ export interface ConfigSlice {
58
83
  name: K,
59
84
  value: IframeConfigs[K]
60
85
  ) => void;
86
+ allProviders: VersionedProviders[];
87
+ buildAndSetProviders: () => void;
88
+ getAvailableProviders: () => VersionedProviders[];
89
+ }
90
+
91
+ function generateProviders(config: WidgetConfig) {
92
+ const options = makeProvidersOptionsFromConfig(config);
93
+ const envs = {
94
+ walletconnect2: {
95
+ WC_PROJECT_ID: options?.walletConnectProjectId || '',
96
+ DISABLE_MODAL_AND_OPEN_LINK:
97
+ options?.walletConnectListedDesktopWalletLink,
98
+ },
99
+ selectedProviders: config.wallets,
100
+ trezor: options?.trezorManifest
101
+ ? { manifest: options.trezorManifest }
102
+ : undefined,
103
+ tonConnect: options?.tonConnect?.manifestUrl
104
+ ? { manifestUrl: options?.tonConnect.manifestUrl }
105
+ : undefined,
106
+ };
107
+ const allProviders = getAllProviders(envs);
108
+ const allBuiltProviders = allProviders.map((build) => build());
109
+
110
+ return allBuiltProviders;
61
111
  }
62
112
 
63
113
  export const createConfigSlice: StateCreatorWithInitialData<
@@ -65,10 +115,15 @@ export const createConfigSlice: StateCreatorWithInitialData<
65
115
  ConfigSlice & SettingsSlice & DataSlice,
66
116
  ConfigSlice
67
117
  > = (initialData, set, get) => {
118
+ const allBuiltProviders = generateProviders({
119
+ ...DEFAULT_CONFIG,
120
+ ...initialData,
121
+ });
68
122
  return {
69
123
  config: { ...DEFAULT_CONFIG, ...initialData },
70
124
  iframe: DEFAULT_IFRAME_CONFIGS,
71
125
  campaignMode: DEFAULT_CAMPAIGN_MODE,
126
+ allProviders: allBuiltProviders,
72
127
  getLiquiditySources: () => {
73
128
  const { config, campaignMode } = get();
74
129
  return campaignMode.liquiditySources?.length
@@ -159,5 +214,26 @@ export const createConfigSlice: StateCreatorWithInitialData<
159
214
  },
160
215
  });
161
216
  },
217
+
218
+ buildAndSetProviders: () => {
219
+ const { config } = get();
220
+ const allBuiltProviders = generateProviders(config);
221
+
222
+ set({
223
+ allProviders: allBuiltProviders,
224
+ });
225
+ },
226
+
227
+ getAvailableProviders: () => {
228
+ const { allProviders, config } = get();
229
+ const options = makeProvidersOptionsFromConfig(config);
230
+
231
+ const availableProviders = matchAndGenerateProviders({
232
+ allProviders,
233
+ configWallets: config.wallets,
234
+ options,
235
+ });
236
+ return availableProviders;
237
+ },
162
238
  };
163
239
  };
@@ -1,3 +1,4 @@
1
+ import type { WidgetConfig } from '../../types';
1
2
  import type { AppStoreState } from '../app';
2
3
  import type { EvmBlockchainMeta, Token } from 'rango-sdk';
3
4
 
@@ -17,6 +18,27 @@ let appStoreState: AppStoreState;
17
18
  let customTokens: [Token, Token, Token];
18
19
  let rangoBlockchain: EvmBlockchainMeta;
19
20
 
21
+ const DEFAULT_CONFIG: WidgetConfig = {
22
+ apiKey: '',
23
+ walletConnectProjectId: 'e24844c5deb5193c1c14840a7af6a40b',
24
+ title: undefined,
25
+ multiWallets: true,
26
+ excludeLiquiditySources: true,
27
+ customDestination: true,
28
+ variant: 'default',
29
+ trezorManifest: {
30
+ appUrl: 'https://widget.rango.exchange/',
31
+ email: 'hi+trezorwidget@rango.exchange',
32
+ },
33
+ tonConnect: {
34
+ manifestUrl:
35
+ 'https://raw.githubusercontent.com/rango-exchange/rango-types/main/assets/manifests/tonconnect-manifest.json',
36
+ },
37
+ features: {
38
+ experimentalWallet: 'enabled',
39
+ },
40
+ };
41
+
20
42
  beforeEach(() => {
21
43
  cacheService.clear();
22
44
  rangoBlockchain = createEvmBlockchain();
@@ -60,7 +82,7 @@ beforeEach(() => {
60
82
  initData._tokensMapByBlockchainName[token.blockchain].push(tokenHash);
61
83
  });
62
84
 
63
- const appStore = createAppStore();
85
+ const appStore = createAppStore(DEFAULT_CONFIG);
64
86
  appStore.setState(initData);
65
87
  appStoreState = appStore.getState();
66
88
  });
@@ -348,8 +348,9 @@ export const createDataSlice: StateCreator<
348
348
  {};
349
349
  const tokens: Token[] = [];
350
350
  const popularTokens: Token[] = response.popularTokens;
351
- const swappers: SwapperMeta[] = response.swappers;
352
-
351
+ const swappers: SwapperMeta[] = response.swappers.filter(
352
+ (swapper) => swapper.enabled
353
+ );
353
354
  const blockchainsWithAtLeastOneToken = new Set();
354
355
 
355
356
  response.tokens.forEach((token) => {
@@ -0,0 +1,9 @@
1
+ import type { ConfigSlice } from './config';
2
+ import type { DataSlice } from './data';
3
+ import type { SettingsSlice } from './settings';
4
+ import type { WalletsSlice } from './wallets';
5
+
6
+ export type AppStoreState = DataSlice &
7
+ ConfigSlice &
8
+ SettingsSlice &
9
+ WalletsSlice;
@@ -0,0 +1,488 @@
1
+ import type { AppStoreState } from './types';
2
+ import type { Token } from 'rango-sdk';
3
+ import type { StateCreator } from 'zustand';
4
+
5
+ import BigNumber from 'bignumber.js';
6
+
7
+ import { eventEmitter } from '../../services/eventEmitter';
8
+ import { httpService } from '../../services/httpService';
9
+ import {
10
+ type Balance,
11
+ type Wallet,
12
+ WalletEventTypes,
13
+ WidgetEvents,
14
+ } from '../../types';
15
+ import { isAccountAndWalletMatched } from '../../utils/wallets';
16
+ import {
17
+ createAssetKey,
18
+ createBalanceKey,
19
+ createBalanceStateForNewAccount,
20
+ extractAssetFromBalanceKey,
21
+ removeBalanceFromAggregatedBalance,
22
+ updateAggregatedBalanceStateForNewAccount,
23
+ } from '../utils/wallets';
24
+
25
+ type WalletAddress = string;
26
+ type TokenAddress = string;
27
+ type TokenSymbol = string;
28
+ type BlockchainId = string;
29
+ /** format: `BlockchainId-TokenAddress-TokenSymbol` */
30
+ export type AssetKey = `${BlockchainId}-${TokenAddress}-${TokenSymbol}`;
31
+ /** format: `BlockchainId-TokenAddress-TokenSymbol-WalletAddress` */
32
+ export type BalanceKey =
33
+ `${BlockchainId}-${TokenAddress}-${TokenSymbol}-${WalletAddress}`;
34
+
35
+ export type BalanceState = {
36
+ [key: BalanceKey]: Balance;
37
+ };
38
+ export type AggregatedBalanceState = {
39
+ [key: AssetKey]: BalanceKey[];
40
+ };
41
+
42
+ export interface ConnectedWallet extends Wallet {
43
+ explorerUrl: string | null;
44
+ selected: boolean;
45
+ loading: boolean;
46
+ error: boolean;
47
+ }
48
+
49
+ export interface WalletsSlice {
50
+ _balances: BalanceState;
51
+ _aggregatedBalances: AggregatedBalanceState;
52
+ connectedWallets: ConnectedWallet[];
53
+ fetchingWallets: boolean;
54
+
55
+ setConnectedWalletAsRefetching: (walletType: string) => void;
56
+ setConnectedWalletHasError: (walletType: string) => void;
57
+ setConnectedWalletRetrievedData: (walletType: string) => void;
58
+ removeBalancesForWallet: (
59
+ walletType: string,
60
+ options?: {
61
+ chains?: string[];
62
+ }
63
+ ) => void;
64
+ addConnectedWallet: (accounts: Wallet[]) => void;
65
+ setWalletsAsSelected: (
66
+ wallets: { walletType: string; chain: string }[]
67
+ ) => void;
68
+ /**
69
+ * Add new accounts to store and fetch balances for them.
70
+ */
71
+ newWalletConnected: (accounts: Wallet[]) => Promise<void>;
72
+ /**
73
+ * Disconnect a wallet and clean up balances after that.
74
+ */
75
+ disconnectWallet: (walletType: string) => void;
76
+ clearConnectedWallet: () => void;
77
+ fetchBalances: (
78
+ accounts: Wallet[],
79
+ options?: { retryOnFailedBalances?: boolean }
80
+ ) => Promise<void>;
81
+ getBalanceFor: (token: Token) => Balance | null;
82
+ getBalances: () => BalanceState;
83
+ }
84
+
85
+ export const createWalletsSlice: StateCreator<
86
+ AppStoreState,
87
+ [],
88
+ [],
89
+ WalletsSlice
90
+ > = (set, get) => ({
91
+ _balances: {},
92
+ _aggregatedBalances: {},
93
+ connectedWallets: [],
94
+ fetchingWallets: false,
95
+
96
+ // Actions
97
+ setConnectedWalletAsRefetching: (walletType: string) => {
98
+ set((state) => {
99
+ return {
100
+ fetchingWallets: true,
101
+ connectedWallets: state.connectedWallets.map((connectedWallet) => {
102
+ if (connectedWallet.walletType === walletType) {
103
+ return {
104
+ ...connectedWallet,
105
+ loading: true,
106
+ error: false,
107
+ };
108
+ }
109
+
110
+ return connectedWallet;
111
+ }),
112
+ };
113
+ });
114
+ },
115
+ setConnectedWalletRetrievedData: (walletType: string) => {
116
+ set((state) => {
117
+ return {
118
+ fetchingWallets: false,
119
+ connectedWallets: state.connectedWallets.map((connectedWallet) => {
120
+ if (connectedWallet.walletType === walletType) {
121
+ return {
122
+ ...connectedWallet,
123
+ loading: false,
124
+ error: false,
125
+ };
126
+ }
127
+
128
+ return connectedWallet;
129
+ }),
130
+ };
131
+ });
132
+ },
133
+ setConnectedWalletHasError: (walletType: string) => {
134
+ set((state) => {
135
+ return {
136
+ fetchingWallets: false,
137
+ connectedWallets: state.connectedWallets.map((connectedWallet) => {
138
+ if (connectedWallet.walletType === walletType) {
139
+ return {
140
+ ...connectedWallet,
141
+ loading: false,
142
+ error: true,
143
+ };
144
+ }
145
+
146
+ return connectedWallet;
147
+ }),
148
+ };
149
+ });
150
+ },
151
+ addConnectedWallet: (accounts: Wallet[]) => {
152
+ /*
153
+ * When we are going to add a new account, there are two thing that can be happens:
154
+ * 1. Wallet hasn't add yet.
155
+ * 2. Wallet has added, and there are some more account that needs to added to connected wallet. consider we've added an ETH and Pol account, then we need to add Arb account later as well.
156
+ *
157
+ * For handling this, we need to only keep not-added-account, then only add those.
158
+ *
159
+ * Note:
160
+ * The second option would be useful for hub particularly.
161
+ */
162
+ const connectedWallets = get().connectedWallets;
163
+ const walletsNeedToBeAdded = accounts.filter(
164
+ (account) =>
165
+ !connectedWallets.some((connectedWallet) =>
166
+ isAccountAndWalletMatched(account, connectedWallet)
167
+ )
168
+ );
169
+
170
+ if (walletsNeedToBeAdded.length > 0) {
171
+ const newConnectedWallets = walletsNeedToBeAdded.map((account) => {
172
+ /*
173
+ * When a wallet is connecting, we will check if there is any `selected` wallet before, if not, we will consider this new wallet as connected.
174
+ * In this way, when user tries to swap, we selected a wallet by default and don't need to do an extra click in ConfirmWalletModal
175
+ */
176
+ const shouldMarkWalletAsSelected = !connectedWallets.some(
177
+ (connectedWallet) =>
178
+ connectedWallet.chain === account.chain &&
179
+ connectedWallet.selected &&
180
+ /**
181
+ * Sometimes, the connect function can be called multiple times for a particular wallet type when using the auto-connect feature.
182
+ * This check is there to make sure the chosen wallet doesn't end up unselected.
183
+ */
184
+ connectedWallet.walletType !== account.walletType
185
+ );
186
+
187
+ return {
188
+ address: account.address,
189
+ chain: account.chain,
190
+ explorerUrl: null,
191
+ walletType: account.walletType,
192
+ selected: shouldMarkWalletAsSelected,
193
+
194
+ loading: false,
195
+ error: false,
196
+ };
197
+ });
198
+
199
+ set((state) => {
200
+ /*
201
+ * If wallet connected before and only need to update the address we should remove the old value and then add new conncted value.
202
+ * This scenario happens when user wants to change account inside the wallet.
203
+ * So the assumption here is the wallet has only one active address for a blockchain at the moment.
204
+ */
205
+ const connectedWalletsWithoutSameWalletAndBlockchain =
206
+ state.connectedWallets.filter((currentConnectedWallet) => {
207
+ return !newConnectedWallets.some(
208
+ (newConnectedWallet) =>
209
+ newConnectedWallet.walletType ===
210
+ currentConnectedWallet.walletType &&
211
+ newConnectedWallet.chain === currentConnectedWallet.chain
212
+ );
213
+ });
214
+
215
+ return {
216
+ connectedWallets: [
217
+ ...connectedWalletsWithoutSameWalletAndBlockchain,
218
+ ...newConnectedWallets,
219
+ ],
220
+ };
221
+ });
222
+ }
223
+ },
224
+ setWalletsAsSelected: (wallets) => {
225
+ const nextConnectedWalletsWithUpdatedSelectedStatus =
226
+ get().connectedWallets.map((connectedWallet) => {
227
+ const walletSelected = !!wallets.find(
228
+ (wallet) =>
229
+ wallet.chain === connectedWallet.chain &&
230
+ wallet.walletType !== connectedWallet.walletType &&
231
+ connectedWallet.selected
232
+ );
233
+ const walletNotSelected = !!wallets.find(
234
+ (wallet) =>
235
+ wallet.chain === connectedWallet.chain &&
236
+ wallet.walletType === connectedWallet.walletType &&
237
+ !connectedWallet.selected
238
+ );
239
+ if (walletSelected) {
240
+ return { ...connectedWallet, selected: false };
241
+ } else if (walletNotSelected) {
242
+ return { ...connectedWallet, selected: true };
243
+ }
244
+
245
+ return connectedWallet;
246
+ });
247
+
248
+ set({
249
+ connectedWallets: nextConnectedWalletsWithUpdatedSelectedStatus,
250
+ });
251
+ },
252
+ newWalletConnected: async (accounts) => {
253
+ eventEmitter.emit(WidgetEvents.WalletEvent, {
254
+ type: WalletEventTypes.CONNECT,
255
+ payload: { walletType: accounts[0].walletType, accounts },
256
+ });
257
+
258
+ get().addConnectedWallet(accounts);
259
+
260
+ void get().fetchBalances(accounts);
261
+ },
262
+ removeBalancesForWallet: (walletType, options) => {
263
+ let walletsNeedsToBeRemoved = get().connectedWallets.filter(
264
+ (connectedWallet) => connectedWallet.walletType === walletType
265
+ );
266
+ /*
267
+ * We only need to delete balances where there is no connected wallets with same chain and address for that balance.
268
+ * Consider both Metamask and Solana having support for `0xblahblahblahblah` for Ethereum.
269
+ * If Phantom is disconnecting, we should keep the balance since Metamask has access to same address yet.
270
+ * So we only delete balance when there is no connected wallet that has access to that specific chain and address.
271
+ */
272
+ get().connectedWallets.forEach((connectedWallet) => {
273
+ if (connectedWallet.walletType !== walletType) {
274
+ walletsNeedsToBeRemoved = walletsNeedsToBeRemoved.filter((wallet) => {
275
+ const isAnotherWalletHasSameAddressAndChain =
276
+ wallet.chain === connectedWallet.chain &&
277
+ wallet.address === connectedWallet.address;
278
+ return !isAnotherWalletHasSameAddressAndChain;
279
+ });
280
+ }
281
+ });
282
+
283
+ if (!!options?.chains && options.chains.length > 0) {
284
+ walletsNeedsToBeRemoved = walletsNeedsToBeRemoved.filter((wallet) => {
285
+ return options.chains?.includes(wallet.chain);
286
+ });
287
+ }
288
+
289
+ const nextBalancesState: BalanceState = {};
290
+ let nextAggregatedBalanceState: AggregatedBalanceState =
291
+ get()._aggregatedBalances;
292
+ const currentBalancesState = get()._balances;
293
+ const balanceKeys = Object.keys(currentBalancesState) as BalanceKey[];
294
+
295
+ balanceKeys.forEach((key) => {
296
+ const asset = extractAssetFromBalanceKey(key);
297
+
298
+ const shouldBalanceBeRemoved = !!walletsNeedsToBeRemoved.find(
299
+ (wallet) =>
300
+ createBalanceKey(wallet.address, {
301
+ address: asset.address,
302
+ blockchain: wallet.chain,
303
+ symbol: asset.symbol,
304
+ }) === key
305
+ );
306
+
307
+ if (!shouldBalanceBeRemoved) {
308
+ nextBalancesState[key] = currentBalancesState[key];
309
+ }
310
+
311
+ // if a balance should be removed, we need to remove its caches in _aggregatedBalances as wel.
312
+ if (shouldBalanceBeRemoved) {
313
+ nextAggregatedBalanceState = removeBalanceFromAggregatedBalance(
314
+ nextAggregatedBalanceState,
315
+ key
316
+ );
317
+ }
318
+ });
319
+ set({
320
+ _balances: nextBalancesState,
321
+ _aggregatedBalances: nextAggregatedBalanceState,
322
+ });
323
+ },
324
+ disconnectWallet: (walletType) => {
325
+ const isTargetWalletExistsInConnectedWallets = get().connectedWallets.find(
326
+ (wallet) => wallet.walletType === walletType
327
+ );
328
+ if (isTargetWalletExistsInConnectedWallets) {
329
+ eventEmitter.emit(WidgetEvents.WalletEvent, {
330
+ type: WalletEventTypes.DISCONNECT,
331
+ payload: { walletType },
332
+ });
333
+
334
+ // This should be called before updating connectedWallets since we need the old state to remove balances.
335
+ get().removeBalancesForWallet(walletType);
336
+
337
+ let targetWalletWasSelectedForBlockchains = get()
338
+ .connectedWallets.filter(
339
+ (connectedWallet) =>
340
+ connectedWallet.selected &&
341
+ connectedWallet.walletType === walletType
342
+ )
343
+ .map((connectedWallet) => connectedWallet.chain);
344
+
345
+ // Remove target wallet from connectedWallets
346
+ let nextConnectedWallets = get().connectedWallets.filter(
347
+ (connectedWallet) => connectedWallet.walletType !== walletType
348
+ );
349
+
350
+ /*
351
+ * If we are disconnecting a wallet that has `selected` for some blockchains,
352
+ * For those blockchains we will fallback to first connected wallet
353
+ * which means selected wallet will change.
354
+ */
355
+ if (targetWalletWasSelectedForBlockchains.length > 0) {
356
+ nextConnectedWallets = nextConnectedWallets.map((connectedWallet) => {
357
+ if (
358
+ targetWalletWasSelectedForBlockchains.includes(
359
+ connectedWallet.chain
360
+ )
361
+ ) {
362
+ targetWalletWasSelectedForBlockchains =
363
+ targetWalletWasSelectedForBlockchains.filter(
364
+ (blockchain) => blockchain !== connectedWallet.chain
365
+ );
366
+ return {
367
+ ...connectedWallet,
368
+ selected: true,
369
+ };
370
+ }
371
+
372
+ return connectedWallet;
373
+ });
374
+ }
375
+
376
+ set({
377
+ connectedWallets: nextConnectedWallets,
378
+ });
379
+ }
380
+ },
381
+ clearConnectedWallet: () => set({ connectedWallets: [] }),
382
+ fetchBalances: async (accounts, options) => {
383
+ // All the `accounts` have same `walletType` so we can pick the first one.
384
+ const walletType = accounts[0].walletType;
385
+
386
+ get().setConnectedWalletAsRefetching(walletType);
387
+
388
+ const addressesToFetch = accounts.map((account) => ({
389
+ address: account.address,
390
+ blockchain: account.chain,
391
+ }));
392
+ const response = await httpService().getWalletsDetails(addressesToFetch);
393
+
394
+ const listWalletsWithBalances = response.wallets;
395
+
396
+ if (listWalletsWithBalances) {
397
+ const { retryOnFailedBalances = true } = options || {};
398
+ if (retryOnFailedBalances) {
399
+ const failedWallets: Wallet[] = listWalletsWithBalances
400
+ .filter((wallet) => wallet.failed)
401
+ .map((wallet) => ({
402
+ chain: wallet.blockChain,
403
+ walletType: walletType,
404
+ address: wallet.address,
405
+ }));
406
+ if (failedWallets.length > 0) {
407
+ void get().fetchBalances(failedWallets, {
408
+ retryOnFailedBalances: false,
409
+ });
410
+ }
411
+ }
412
+
413
+ let nextBalances: BalanceState = {};
414
+ let nextAggregatedBalances: AggregatedBalanceState =
415
+ get()._aggregatedBalances;
416
+ listWalletsWithBalances.forEach((wallet) => {
417
+ if (wallet.failed) {
418
+ return;
419
+ }
420
+
421
+ const balancesForWallet = createBalanceStateForNewAccount(wallet, get);
422
+
423
+ nextAggregatedBalances = updateAggregatedBalanceStateForNewAccount(
424
+ nextAggregatedBalances,
425
+ balancesForWallet
426
+ );
427
+
428
+ nextBalances = {
429
+ ...nextBalances,
430
+ ...balancesForWallet,
431
+ };
432
+ });
433
+
434
+ set((state) => ({
435
+ _balances: {
436
+ ...state._balances,
437
+ ...nextBalances,
438
+ },
439
+ _aggregatedBalances: nextAggregatedBalances,
440
+ }));
441
+
442
+ get().setConnectedWalletRetrievedData(walletType);
443
+ } else {
444
+ get().setConnectedWalletHasError(walletType);
445
+ throw new Error(
446
+ `We couldn't fetch your account balances. Seem there is no information on blockchain for them yet.`
447
+ );
448
+ }
449
+ },
450
+ getBalances: () => {
451
+ return get()._balances;
452
+ },
453
+ getBalanceFor: (token) => {
454
+ const balances = get().getBalances();
455
+
456
+ /*
457
+ * The old implementation wasn't considering user's address.
458
+ * it can be problematic when two separate address has same token, both of them will override on same key.
459
+ *
460
+ * For keeping the same behavior, here we pick the most amount and also will not consider user's address in key.
461
+ */
462
+
463
+ // Note: balance key is created using asset key + wallet address
464
+ const assetKey = createAssetKey(token);
465
+ const targetBalanceKeys = get()._aggregatedBalances[assetKey] || [];
466
+
467
+ if (targetBalanceKeys.length === 0) {
468
+ return null;
469
+ } else if (targetBalanceKeys.length === 1) {
470
+ const targetKey = targetBalanceKeys[0];
471
+ return balances[targetKey];
472
+ }
473
+
474
+ // If there are multiple balances for an specific token, we pick the maximum.
475
+ const firstTargetBalance = balances[targetBalanceKeys[0]];
476
+ let maxBalance: Balance = firstTargetBalance;
477
+ targetBalanceKeys.forEach((targetBalanceKey) => {
478
+ const currentBalance = balances[targetBalanceKey];
479
+ const currentBalanceAmount = new BigNumber(currentBalance.amount);
480
+ const prevBalanceAmount = new BigNumber(maxBalance.amount);
481
+
482
+ if (currentBalanceAmount.isGreaterThan(prevBalanceAmount)) {
483
+ maxBalance = currentBalance;
484
+ }
485
+ });
486
+ return maxBalance;
487
+ },
488
+ });