@rango-dev/widget-embedded 0.36.1-next.9 → 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 (86) hide show
  1. package/dist/QueueManager.d.ts.map +1 -1
  2. package/dist/components/ConfirmWalletsModal/ConfirmWalletsModal.d.ts.map +1 -1
  3. package/dist/components/Quote/Quote.styles.d.ts +1 -1
  4. package/dist/components/QuoteWarningsAndErrors/QuoteWarningsAndErrors.helpers.d.ts.map +1 -1
  5. package/dist/components/Quotes/Quotes.d.ts.map +1 -1
  6. package/dist/components/RefreshModal/RefreshModal.styles.d.ts +1 -1
  7. package/dist/components/SwapDetails/SwapDetails.d.ts.map +1 -1
  8. package/dist/components/SwapDetailsModal/SwapDetailsCompleteModal.d.ts.map +1 -1
  9. package/dist/components/WalletStatefulConnect/Namespaces.d.ts.map +1 -1
  10. package/dist/constants/quote.d.ts +8 -0
  11. package/dist/constants/quote.d.ts.map +1 -1
  12. package/dist/containers/QuoteInfo/QuoteInfo.d.ts.map +1 -1
  13. package/dist/containers/Wallets/Wallets.d.ts.map +1 -1
  14. package/dist/containers/WidgetInfo/WidgetInfo.helpers.d.ts +1 -1
  15. package/dist/hooks/useConfirmSwap/useConfirmSwap.d.ts.map +1 -1
  16. package/dist/hooks/useConfirmSwap/useConfirmSwap.helpers.d.ts +6 -4
  17. package/dist/hooks/useConfirmSwap/useConfirmSwap.helpers.d.ts.map +1 -1
  18. package/dist/hooks/useFetchApiConfig.d.ts.map +1 -1
  19. package/dist/hooks/useStatefulConnect/useStatefulConnect.d.ts.map +1 -1
  20. package/dist/hooks/useStatefulConnect/useStatefulConnect.types.d.ts +2 -4
  21. package/dist/hooks/useStatefulConnect/useStatefulConnect.types.d.ts.map +1 -1
  22. package/dist/hooks/useSwapInput.d.ts.map +1 -1
  23. package/dist/hooks/useWalletList.d.ts.map +1 -1
  24. package/dist/hooks/useWalletProviders/useWalletProviders.d.ts +1 -1
  25. package/dist/hooks/useWalletProviders/useWalletProviders.d.ts.map +1 -1
  26. package/dist/index.js +2 -2
  27. package/dist/index.js.map +4 -4
  28. package/dist/pages/ConfirmSwapPage.d.ts.map +1 -1
  29. package/dist/store/quote.d.ts.map +1 -1
  30. package/dist/store/slices/config.d.ts +4 -0
  31. package/dist/store/slices/config.d.ts.map +1 -1
  32. package/dist/store/slices/wallets.d.ts +3 -1
  33. package/dist/store/slices/wallets.d.ts.map +1 -1
  34. package/dist/store/ui.d.ts +4 -0
  35. package/dist/store/ui.d.ts.map +1 -1
  36. package/dist/types/quote.d.ts +8 -17
  37. package/dist/types/quote.d.ts.map +1 -1
  38. package/dist/types/wallets.d.ts +1 -6
  39. package/dist/types/wallets.d.ts.map +1 -1
  40. package/dist/utils/providers.d.ts +6 -2
  41. package/dist/utils/providers.d.ts.map +1 -1
  42. package/dist/utils/quote.d.ts +5 -6
  43. package/dist/utils/quote.d.ts.map +1 -1
  44. package/dist/utils/swap.d.ts +4 -4
  45. package/dist/utils/swap.d.ts.map +1 -1
  46. package/dist/utils/wallets.d.ts.map +1 -1
  47. package/dist/widget-embedded.build.json +1 -1
  48. package/package.json +7 -7
  49. package/src/QueueManager.tsx +11 -10
  50. package/src/components/ConfirmWalletsModal/ConfirmWalletsModal.tsx +2 -19
  51. package/src/components/ConfirmWalletsModal/WalletList.tsx +1 -1
  52. package/src/components/QuoteWarningsAndErrors/QuoteWarningsAndErrors.helpers.ts +42 -22
  53. package/src/components/Quotes/Quotes.tsx +2 -3
  54. package/src/components/SwapDetails/SwapDetails.tsx +10 -7
  55. package/src/components/SwapDetailsModal/SwapDetailsCompleteModal.tsx +26 -13
  56. package/src/components/WalletStatefulConnect/Namespaces.tsx +30 -37
  57. package/src/constants/quote.ts +23 -0
  58. package/src/containers/QuoteInfo/QuoteInfo.tsx +3 -9
  59. package/src/containers/Wallets/Wallets.tsx +63 -3
  60. package/src/containers/WidgetInfo/WidgetInfo.helpers.ts +2 -2
  61. package/src/hooks/useConfirmSwap/useConfirmSwap.helpers.ts +29 -66
  62. package/src/hooks/useConfirmSwap/useConfirmSwap.ts +10 -15
  63. package/src/hooks/useFetchApiConfig.ts +5 -1
  64. package/src/hooks/useStatefulConnect/useStatefulConnect.ts +20 -22
  65. package/src/hooks/useStatefulConnect/useStatefulConnect.types.ts +2 -4
  66. package/src/hooks/useSwapInput.ts +2 -9
  67. package/src/hooks/useWalletList.ts +6 -6
  68. package/src/hooks/useWalletProviders/useWalletProviders.ts +7 -7
  69. package/src/pages/ConfirmSwapPage.tsx +7 -15
  70. package/src/store/quote.ts +3 -13
  71. package/src/store/slices/config.ts +73 -0
  72. package/src/store/slices/data.test.ts +23 -1
  73. package/src/store/slices/wallets.ts +13 -2
  74. package/src/store/ui.ts +6 -0
  75. package/src/types/quote.ts +10 -24
  76. package/src/types/wallets.ts +1 -6
  77. package/src/utils/providers.ts +66 -70
  78. package/src/utils/quote.ts +57 -45
  79. package/src/utils/swap.ts +55 -36
  80. package/src/utils/wallets.ts +2 -4
  81. package/dist/constants/warnings.d.ts +0 -3
  82. package/dist/constants/warnings.d.ts.map +0 -1
  83. package/dist/utils/hub.d.ts +0 -4
  84. package/dist/utils/hub.d.ts.map +0 -1
  85. package/src/constants/warnings.ts +0 -26
  86. package/src/utils/hub.ts +0 -21
package/src/store/ui.ts CHANGED
@@ -12,12 +12,14 @@ interface UiState {
12
12
  tabManagerInitiated: boolean;
13
13
  showActivateTabModal: boolean;
14
14
  watermark: Watermark;
15
+ showProfileBanner: boolean;
15
16
  activateCurrentTab: (
16
17
  setCurrentTabAsActive: () => void,
17
18
  hasRunningSwaps: boolean
18
19
  ) => void;
19
20
  setShowActivateTabModal: (flag: boolean) => void;
20
21
  setWatermark: (watermark: Watermark) => void;
22
+ setShowProfileBanner: (showProfileBanner: boolean) => void;
21
23
  }
22
24
 
23
25
  export const useUiStore = createSelectors(
@@ -26,6 +28,7 @@ export const useUiStore = createSelectors(
26
28
  tabManagerInitiated: false,
27
29
  showActivateTabModal: false,
28
30
  watermark: 'NONE',
31
+ showProfileBanner: false,
29
32
  fetchingApiConfig: false,
30
33
  activateCurrentTab: (setCurrentTabAsActive, hasRunningSwaps) => {
31
34
  const { showActivateTabModal } = get();
@@ -42,6 +45,9 @@ export const useUiStore = createSelectors(
42
45
  setWatermark: (watermark) => {
43
46
  set({ watermark });
44
47
  },
48
+ setShowProfileBanner: (showProfileBanner) => {
49
+ set({ showProfileBanner });
50
+ },
45
51
  }))
46
52
  );
47
53
 
@@ -51,29 +51,9 @@ export enum QuoteWarningType {
51
51
  UNKNOWN_PRICE,
52
52
  INSUFFICIENT_SLIPPAGE,
53
53
  HIGH_SLIPPAGE,
54
+ EXCESSIVE_OUTPUT_AMOUNT_CHANGE,
54
55
  }
55
56
 
56
- export enum QuoteUpdateType {
57
- QUOTE_UPDATED,
58
- QUOTE_SWAPPERS_UPDATED,
59
- QUOTE_COINS_UPDATED,
60
- QUOTE_AND_OUTPUT_AMOUNT_UPDATED,
61
- QUOTE_UPDATED_WITH_HIGH_VALUE_LOSS,
62
- }
63
-
64
- export type QuoteUpdateWarning =
65
- | {
66
- type: QuoteUpdateType.QUOTE_AND_OUTPUT_AMOUNT_UPDATED;
67
- newOutputAmount: string;
68
- percentageChange: string;
69
- }
70
- | {
71
- type: Exclude<
72
- QuoteUpdateType,
73
- QuoteUpdateType.QUOTE_AND_OUTPUT_AMOUNT_UPDATED
74
- >;
75
- };
76
-
77
57
  export type RecommendedSlippages = Map<number, string>;
78
58
 
79
59
  export type InsufficientSlippageWarning = {
@@ -100,15 +80,21 @@ export type UnknownPriceWarning = {
100
80
  type: QuoteWarningType.UNKNOWN_PRICE;
101
81
  };
102
82
 
83
+ export type ExcessiveOutputAmountChange = {
84
+ type: QuoteWarningType.EXCESSIVE_OUTPUT_AMOUNT_CHANGE;
85
+ usdValueChange: string;
86
+ percentageChange: string;
87
+ };
88
+
103
89
  export type QuoteWarning =
104
90
  | HighValueLossWarning
91
+ | ExcessiveOutputAmountChange
92
+ | UnknownPriceWarning
105
93
  | InsufficientSlippageWarning
106
- | HighSlippageWarning
107
- | UnknownPriceWarning;
94
+ | HighSlippageWarning;
108
95
 
109
96
  export type ConfirmSwapWarnings = {
110
97
  quote: QuoteWarning | null;
111
- quoteUpdate: QuoteUpdateWarning | null;
112
98
  balance: { messages: string[] } | null;
113
99
  };
114
100
 
@@ -1,5 +1,4 @@
1
1
  import type { WalletInfo } from '@rango-dev/ui';
2
- import type { Namespace } from '@rango-dev/wallets-core/namespaces/common';
3
2
  import type { WalletType } from '@rango-dev/wallets-shared';
4
3
 
5
4
  export interface Wallet {
@@ -25,8 +24,4 @@ export type TokensBalance = {
25
24
  [key: TokenHash]: Balance;
26
25
  };
27
26
 
28
- export type WalletInfoWithExtra = WalletInfo & {
29
- namespaces?: Namespace[];
30
- singleNamespace?: boolean;
31
- needsDerivationPath?: boolean;
32
- };
27
+ export type WalletInfoWithExtra = WalletInfo;
@@ -1,7 +1,6 @@
1
1
  import type { WidgetConfig } from '../types';
2
2
  import type { LegacyProviderInterface } from '@rango-dev/wallets-core/legacy';
3
3
 
4
- import { allProviders } from '@rango-dev/provider-all';
5
4
  import {
6
5
  defineVersions,
7
6
  pickVersion,
@@ -26,69 +25,69 @@ export interface ProvidersOptions {
26
25
  *
27
26
  */
28
27
  type BothProvidersInterface = LegacyProviderInterface | Provider;
29
- export function matchAndGenerateProviders(
30
- providers: WidgetConfig['wallets'],
31
- options?: ProvidersOptions
32
- ): VersionedProviders[] {
33
- const envs = {
34
- walletconnect2: {
35
- WC_PROJECT_ID: options?.walletConnectProjectId || '',
36
- DISABLE_MODAL_AND_OPEN_LINK:
37
- options?.walletConnectListedDesktopWalletLink,
38
- },
39
- selectedProviders: providers,
40
- trezor: options?.trezorManifest
41
- ? { manifest: options.trezorManifest }
42
- : undefined,
43
- tonConnect: options?.tonConnect?.manifestUrl
44
- ? { manifestUrl: options?.tonConnect.manifestUrl }
45
- : undefined,
46
- };
47
-
48
- const all = allProviders(envs);
49
-
50
- if (providers) {
28
+ export function matchAndGenerateProviders({
29
+ allProviders,
30
+ configWallets,
31
+ options,
32
+ }: {
33
+ allProviders: VersionedProviders[];
34
+ configWallets: WidgetConfig['wallets'];
35
+ options?: ProvidersOptions;
36
+ }): VersionedProviders[] {
37
+ if (configWallets) {
38
+ /*
39
+ * If `wallets` is included in widget config,
40
+ * allProviders should be filtered based on wallets list
41
+ */
51
42
  const selectedProviders: VersionedProviders[] = [];
52
43
 
53
- providers.forEach((requestedProvider) => {
44
+ configWallets.forEach((requestedWallet) => {
54
45
  /*
55
46
  * There are two types of provider we get, the first one is only passing the wallet name
56
47
  * then we will match the wallet name with our providers (@rango-dev/provider-*).
57
48
  * The second way is passing a custom provider which implemented ProviderInterface.
58
49
  */
59
- if (typeof requestedProvider === 'string') {
60
- const result: BothProvidersInterface | undefined =
61
- pickVersionWithFallbackToLegacy(all, options).find((provider) => {
62
- if (provider instanceof Provider) {
63
- return provider.id === requestedProvider;
64
- }
65
- return provider.config.type === requestedProvider;
66
- });
50
+ if (typeof requestedWallet === 'string') {
51
+ const result = allProviders.find((provider) => {
52
+ /*
53
+ * To find a provider in allProviders,
54
+ * a version of each provider should be picked
55
+ * and validated based on that version scheme.
56
+ * If the corresponding provider to a wallet was found in allProvider,
57
+ * it will be add to selected providers.
58
+ */
59
+ const versionedProvider = pickProviderVersionWithFallbackToLegacy(
60
+ provider,
61
+ options
62
+ );
63
+ if (versionedProvider instanceof Provider) {
64
+ return versionedProvider.id === requestedWallet;
65
+ }
66
+ return versionedProvider.config.type === requestedWallet;
67
+ });
67
68
 
69
+ /*
70
+ * A provider may have multiple versions
71
+ * (e.g., 0.0, also known as legacy, and 1.0, also known as hub).
72
+ * We should ensure that all existing versions of a provider are added to selectedProviders.
73
+ */
68
74
  if (result) {
69
- if (result instanceof Provider) {
70
- selectedProviders.push(
71
- defineVersions().version('1.0.0', result).build()
72
- );
73
- } else {
74
- selectedProviders.push(
75
- defineVersions().version('0.0.0', result).build()
76
- );
77
- }
75
+ selectedProviders.push(result);
78
76
  } else {
79
77
  console.warn(
80
- `Couldn't find ${requestedProvider} provider. Please make sure you are passing the correct name.`
78
+ // A provider name is included in config but was not found in allProviders
79
+ `Couldn't find ${requestedWallet} provider. Please make sure you are passing the correct name.`
81
80
  );
82
81
  }
83
82
  } else {
84
83
  // It's a custom provider so we directly push it to the list.
85
- if (requestedProvider instanceof Provider) {
84
+ if (requestedWallet instanceof Provider) {
86
85
  selectedProviders.push(
87
- defineVersions().version('1.0.0', requestedProvider).build()
86
+ defineVersions().version('1.0.0', requestedWallet).build()
88
87
  );
89
88
  } else {
90
89
  selectedProviders.push(
91
- defineVersions().version('0.0.0', requestedProvider).build()
90
+ defineVersions().version('0.0.0', requestedWallet).build()
92
91
  );
93
92
  }
94
93
  }
@@ -97,40 +96,37 @@ export function matchAndGenerateProviders(
97
96
  return selectedProviders;
98
97
  }
99
98
 
100
- return all;
99
+ return allProviders;
101
100
  }
102
101
 
103
- // TODO: this is a duplication with what we do in core.
104
- function pickVersionWithFallbackToLegacy(
105
- providers: VersionedProviders[],
102
+ function pickProviderVersionWithFallbackToLegacy(
103
+ provider: VersionedProviders,
106
104
  options?: ProvidersOptions
107
- ): BothProvidersInterface[] {
105
+ ): BothProvidersInterface {
108
106
  const { experimentalWallet = 'enabled' } = options || {};
107
+ const version = experimentalWallet == 'disabled' ? '0.0.0' : '1.0.0';
109
108
 
110
- return providers.map((provider) => {
111
- const version = experimentalWallet == 'disabled' ? '0.0.0' : '1.0.0';
112
- try {
113
- return pickVersion(provider, version)[1];
114
- } catch {
115
- // Fallback to legacy version, if target version doesn't exists.
116
- return pickVersion(provider, '0.0.0')[1];
117
- }
118
- });
109
+ try {
110
+ return pickVersion(provider, version)[1];
111
+ } catch {
112
+ // Fallback to legacy version, if target version doesn't exists.
113
+ return pickVersion(provider, '0.0.0')[1];
114
+ }
119
115
  }
120
116
 
121
117
  export function configWalletsToWalletName(
122
- config: WidgetConfig['wallets'],
118
+ providers: VersionedProviders[],
123
119
  options?: ProvidersOptions
124
120
  ): string[] {
125
- const providers = pickVersionWithFallbackToLegacy(
126
- matchAndGenerateProviders(config, options),
127
- options
128
- );
129
- const names = providers.map((provider) => {
130
- if (provider instanceof Provider) {
131
- return provider.id;
132
- }
133
- return provider.config.type;
134
- });
121
+ const names = providers
122
+ .map((provider) =>
123
+ pickProviderVersionWithFallbackToLegacy(provider, options)
124
+ )
125
+ .map((provider) => {
126
+ if (provider instanceof Provider) {
127
+ return provider.id;
128
+ }
129
+ return provider.config.type;
130
+ });
135
131
  return names;
136
132
  }
@@ -15,7 +15,6 @@ import type {
15
15
  MultiRouteSimulationResult,
16
16
  PreferenceType,
17
17
  RouteTag,
18
- Token,
19
18
  } from 'rango-sdk';
20
19
  import type { PendingSwap } from 'rango-types';
21
20
 
@@ -29,30 +28,19 @@ import { QuoteWarningType } from '../types';
29
28
 
30
29
  import { areEqual } from './common';
31
30
  import { createTokenHash, findBlockchain } from './meta';
31
+ import { numberToString } from './numbers';
32
32
  import {
33
- calcOutputUsdValue,
34
33
  checkSlippageWarnings,
35
34
  getMinRequiredSlippage,
36
35
  getPercentageChange,
37
36
  getTotalFeeInUsd,
37
+ getUsdInputFrom,
38
+ getUsdOutputFrom,
38
39
  hasHighValueLoss,
39
40
  hasProperSlippage,
41
+ isOutputAmountChangedExcessively,
40
42
  } from './swap';
41
43
 
42
- export function getQuoteToTokenUsdPrice(
43
- quote: SelectedQuote | null
44
- ): number | null | undefined {
45
- const swaps = quote?.swaps || [];
46
- return swaps[swaps.length - 1].to.usdPrice;
47
- }
48
-
49
- export function getQuoteFromTokenUsdPrice(
50
- quote: SelectedQuote | null
51
- ): number | null | undefined {
52
- const swaps = quote?.swaps || [];
53
- return swaps[0].from.usdPrice;
54
- }
55
-
56
44
  export function isNumberOfSwapsChanged(
57
45
  quoteA: SelectedQuote,
58
46
  quoteB: SelectedQuote
@@ -195,56 +183,73 @@ export function createRetryQuote(
195
183
  };
196
184
  }
197
185
 
198
- export function generateQuoteWarnings(
199
- quote: SelectedQuote,
200
- params: {
201
- fromToken: Token;
202
- toToken: Token;
203
- findToken: FindToken;
204
- userSlippage: number;
205
- }
206
- ): QuoteWarning | null {
207
- const { fromToken, toToken, findToken, userSlippage } = params;
208
- const inputUsdValue = calcOutputUsdValue(
209
- quote.requestAmount,
210
- getQuoteFromTokenUsdPrice(quote) || fromToken?.usdPrice
211
- );
212
- const outputUsdValue = calcOutputUsdValue(
213
- quote.outputAmount,
214
- getQuoteToTokenUsdPrice(quote) || toToken?.usdPrice
215
- );
216
-
217
- if (!!quote && inputUsdValue && outputUsdValue) {
186
+ export function generateQuoteWarnings(params: {
187
+ previousQuote?: SelectedQuote;
188
+ currentQuote: SelectedQuote;
189
+ findToken: FindToken;
190
+ userSlippage: number;
191
+ }): QuoteWarning | null {
192
+ const { previousQuote, currentQuote, findToken, userSlippage } = params;
193
+ const usdInput = getUsdInputFrom(currentQuote);
194
+ const usdOutput = getUsdOutputFrom(currentQuote);
195
+
196
+ if (!!currentQuote && usdInput && usdOutput) {
218
197
  const priceImpact = getPriceImpact(
219
- inputUsdValue.toString(),
220
- outputUsdValue.toString()
198
+ usdInput.toString(),
199
+ usdOutput.toString()
221
200
  );
222
201
  const highValueLoss =
223
- !!priceImpact && hasHighValueLoss(inputUsdValue, priceImpact);
202
+ !!priceImpact && hasHighValueLoss(usdInput, priceImpact);
224
203
 
225
204
  if (highValueLoss) {
226
- const totalFee = getTotalFeeInUsd(quote?.swaps, findToken);
205
+ const totalFee = getTotalFeeInUsd(currentQuote?.swaps, findToken);
227
206
  const warningLevel = getPriceImpactLevel(priceImpact);
228
207
  return {
229
208
  type: QuoteWarningType.HIGH_VALUE_LOSS,
230
- inputUsdValue,
231
- outputUsdValue,
209
+ inputUsdValue: usdInput,
210
+ outputUsdValue: usdOutput,
232
211
  priceImpact,
233
212
  totalFee,
234
213
  warningLevel,
235
214
  };
236
215
  }
237
- } else if (quote && (!inputUsdValue || !outputUsdValue)) {
216
+ }
217
+
218
+ if (
219
+ previousQuote &&
220
+ isOutputAmountChangedExcessively(previousQuote, currentQuote)
221
+ ) {
222
+ return {
223
+ type: QuoteWarningType.EXCESSIVE_OUTPUT_AMOUNT_CHANGE,
224
+ usdValueChange: numberToString(
225
+ getUsdOutputFrom(currentQuote)
226
+ ?.minus(getUsdOutputFrom(previousQuote) ?? 0)
227
+ .toString() ?? '0',
228
+ null,
229
+ 2
230
+ ),
231
+ percentageChange: numberToString(
232
+ getPriceImpact(
233
+ getUsdOutputFrom(previousQuote) ?? '1',
234
+ getUsdOutputFrom(currentQuote) ?? '1'
235
+ ),
236
+ null,
237
+ 2
238
+ ),
239
+ };
240
+ }
241
+
242
+ if (currentQuote && (!usdInput || !usdOutput)) {
238
243
  return { type: QuoteWarningType.UNKNOWN_PRICE };
239
244
  }
240
245
 
241
- const minRequiredSlippage = getMinRequiredSlippage(quote.swaps);
246
+ const minRequiredSlippage = getMinRequiredSlippage(currentQuote.swaps);
242
247
  const highSlippage = userSlippage > HIGH_SLIPPAGE;
243
248
 
244
249
  if (!hasProperSlippage(params.userSlippage.toString(), minRequiredSlippage)) {
245
250
  return {
246
251
  type: QuoteWarningType.INSUFFICIENT_SLIPPAGE,
247
- recommendedSlippages: checkSlippageWarnings(quote, userSlippage),
252
+ recommendedSlippages: checkSlippageWarnings(currentQuote, userSlippage),
248
253
  minRequiredSlippage: minRequiredSlippage,
249
254
  };
250
255
  } else if (
@@ -260,6 +265,13 @@ export function generateQuoteWarnings(
260
265
  return null;
261
266
  }
262
267
 
268
+ export function isQuoteWarningConfirmationRequired(warning: QuoteWarning) {
269
+ const WARNINGS_NOT_REQUIRING_CONFIRMATION = [
270
+ QuoteWarningType.EXCESSIVE_OUTPUT_AMOUNT_CHANGE,
271
+ ];
272
+ return !WARNINGS_NOT_REQUIRING_CONFIRMATION.includes(warning.type);
273
+ }
274
+
263
275
  export function getPriceImpact(
264
276
  inputUsdValue: BigNumber | string | null,
265
277
  outputUsdValue: BigNumber | string | null
package/src/utils/swap.ts CHANGED
@@ -1,5 +1,3 @@
1
- /* eslint-disable @typescript-eslint/no-magic-numbers */
2
- import type { FeesGroup, NameOfFees } from '../constants/quote';
3
1
  import type { FetchStatus, FindToken } from '../store/slices/data';
4
2
  import type { ConnectedWallet } from '../store/slices/wallets';
5
3
  import type {
@@ -34,6 +32,14 @@ import { PendingSwapNetworkStatus } from 'rango-types';
34
32
  import { errorMessages } from '../constants/errors';
35
33
  import { swapButtonTitles } from '../constants/messages';
36
34
  import { ZERO } from '../constants/numbers';
35
+ import {
36
+ type FeesGroup,
37
+ HIGH_FEE_THRESHOLD_USD,
38
+ HIGH_VALUE_LOSS_CRITERIA,
39
+ type NameOfFees,
40
+ OUTPUT_CHANGE_WARNING_CRITERIA,
41
+ PERCENT_MULTIPLIER,
42
+ } from '../constants/quote';
37
43
  import {
38
44
  BALANCE_MAX_DECIMALS,
39
45
  BALANCE_MIN_DECIMALS,
@@ -43,7 +49,7 @@ import {
43
49
 
44
50
  import { getBlockchainShortNameFor, isValidTokenAddress } from './meta';
45
51
  import { numberToString } from './numbers';
46
- import { getPriceImpact, getRequiredBalanceOfWallet } from './quote';
52
+ import { getRequiredBalanceOfWallet } from './quote';
47
53
  import { getQuoteWallets } from './wallets';
48
54
 
49
55
  export function getOutputRatio(
@@ -61,7 +67,7 @@ export function getOutputRatio(
61
67
  return outputUsdValue
62
68
  .div(inputUsdValue)
63
69
  .minus(1)
64
- .multipliedBy(100)
70
+ .multipliedBy(PERCENT_MULTIPLIER)
65
71
  .toNumber();
66
72
  }
67
73
 
@@ -69,12 +75,16 @@ export function hasHighValueLoss(
69
75
  inputUsdValue: BigNumber | null,
70
76
  priceImpact: number
71
77
  ): boolean {
72
- return (
73
- ((parseInt(priceImpact.toFixed(2) || '0') <= -10 &&
74
- inputUsdValue?.gte(new BigNumber(400))) ||
75
- (parseInt(priceImpact.toFixed(2) || '0') <= -5 &&
76
- inputUsdValue?.gte(new BigNumber(1000)))) ??
77
- false
78
+ if (!inputUsdValue) {
79
+ return false;
80
+ }
81
+
82
+ const formattedPriceImpact = parseInt(priceImpact.toFixed(2) || '0');
83
+
84
+ return HIGH_VALUE_LOSS_CRITERIA.some(
85
+ ({ threshold, minInput }) =>
86
+ formattedPriceImpact <= threshold &&
87
+ inputUsdValue.gte(new BigNumber(minInput))
78
88
  );
79
89
  }
80
90
 
@@ -328,7 +338,7 @@ export function hasHighFee(totalFeeInUsd: BigNumber | null) {
328
338
  if (!totalFeeInUsd) {
329
339
  return false;
330
340
  }
331
- return !totalFeeInUsd.lt(new BigNumber(30));
341
+ return !totalFeeInUsd.lt(new BigNumber(HIGH_FEE_THRESHOLD_USD));
332
342
  }
333
343
 
334
344
  export function hasSlippageError(
@@ -480,8 +490,7 @@ export function createQuoteRequestBody(params: {
480
490
  addresses: [wallet.address],
481
491
  });
482
492
  });
483
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
484
- // @ts-ignore
493
+
485
494
  const requestBody: BestRouteRequest = {
486
495
  amount: inputAmount.toString(),
487
496
  affiliateRef: affiliateRef ?? undefined,
@@ -535,33 +544,52 @@ export function getWalletsForNewSwap(selectedWallets: Wallet[]) {
535
544
  return wallets;
536
545
  }
537
546
 
538
- export function getQuoteOutputAmount(quote: SelectedQuote) {
539
- return quote?.outputAmount || null;
547
+ export function getUsdInputFrom(quote: SelectedQuote): BigNumber | undefined {
548
+ const inputAmount = quote.requestAmount;
549
+ const inputTokenUsdPrice = quote.swaps[0].from.usdPrice;
550
+ if (!inputAmount || !inputTokenUsdPrice) {
551
+ return;
552
+ }
553
+ return new BigNumber(inputAmount).multipliedBy(inputTokenUsdPrice);
554
+ }
555
+
556
+ export function getUsdOutputFrom(quote: SelectedQuote): BigNumber | undefined {
557
+ const outputAmount = quote?.outputAmount || null;
558
+ const outputTokenUsdPrice = quote.swaps[quote.swaps.length - 1].to.usdPrice;
559
+ if (!outputAmount || !outputTokenUsdPrice) {
560
+ return;
561
+ }
562
+ return new BigNumber(outputAmount).multipliedBy(outputTokenUsdPrice);
540
563
  }
541
564
 
542
565
  export function getPercentageChange(input: string, output: string) {
543
566
  return new BigNumber(output)
544
567
  .div(new BigNumber(input))
545
568
  .minus(1)
546
- .multipliedBy(100)
569
+ .multipliedBy(PERCENT_MULTIPLIER)
547
570
  .toNumber();
548
571
  }
549
572
 
550
- export function isOutputAmountChangedALot(
551
- oldQuote: SelectedQuote,
552
- newQuote: SelectedQuote
573
+ export function isOutputAmountChangedExcessively(
574
+ previousQuote: SelectedQuote,
575
+ currentQuote: SelectedQuote
553
576
  ) {
554
- const oldOutputAmount = getQuoteOutputAmount(oldQuote);
555
- const newOutputAmount = getQuoteOutputAmount(newQuote);
556
- if (!oldOutputAmount || !newOutputAmount) {
577
+ const usdInput = getUsdInputFrom(previousQuote);
578
+ const previousUsdOutput = getUsdOutputFrom(previousQuote);
579
+ const currentUsdOutput = getUsdOutputFrom(currentQuote);
580
+ if (!usdInput || !previousUsdOutput || !currentUsdOutput) {
557
581
  return false;
558
582
  }
559
- const percentageChange = getPriceImpact(oldOutputAmount, newOutputAmount);
560
- if (!percentageChange) {
561
- return true;
562
- }
563
583
 
564
- return percentageChange <= -1;
584
+ const percentageChange = getPercentageChange(
585
+ previousUsdOutput.toString(),
586
+ currentUsdOutput.toString()
587
+ );
588
+
589
+ return OUTPUT_CHANGE_WARNING_CRITERIA.some(
590
+ ({ threshold, minInput }) =>
591
+ percentageChange <= threshold && usdInput.isGreaterThanOrEqualTo(minInput)
592
+ );
565
593
  }
566
594
 
567
595
  export function generateBalanceWarnings(
@@ -623,15 +651,6 @@ export function generateBalanceWarnings(
623
651
  });
624
652
  }
625
653
 
626
- export function calcOutputUsdValue(
627
- outputAmount?: string,
628
- tokenPrice?: number | null
629
- ) {
630
- const amount = !!outputAmount ? new BigNumber(outputAmount) : ZERO;
631
-
632
- return amount.multipliedBy(tokenPrice || 0);
633
- }
634
-
635
654
  export function isNetworkStatusInWarningState(
636
655
  pendingSwapStep: PendingSwapStep | null
637
656
  ): boolean {
@@ -87,8 +87,7 @@ export function mapWalletTypesToWalletInfo(
87
87
  img: image,
88
88
  installLink,
89
89
  showOnMobile,
90
- namespaces,
91
- singleNamespace,
90
+ needsNamespace,
92
91
  supportedChains,
93
92
  needsDerivationPath,
94
93
  properties,
@@ -106,8 +105,7 @@ export function mapWalletTypesToWalletInfo(
106
105
  state,
107
106
  type,
108
107
  showOnMobile,
109
- namespaces,
110
- singleNamespace,
108
+ needsNamespace,
111
109
  blockchainTypes,
112
110
  needsDerivationPath,
113
111
  properties,
@@ -1,3 +0,0 @@
1
- import type { QuoteUpdateWarning } from '../types';
2
- export declare function getQuoteUpdateWarningMessage(warning: QuoteUpdateWarning): string;
3
- //# sourceMappingURL=warnings.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"warnings.d.ts","sourceRoot":"","sources":["../../src/constants/warnings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAMnD,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,kBAAkB,UAmBvE"}
@@ -1,4 +0,0 @@
1
- import type { CommonNamespaceKeys } from '@rango-dev/wallets-core';
2
- import type { Namespace } from '@rango-dev/wallets-core/namespaces/common';
3
- export declare function convertCommonNamespacesKeysToLegacyNamespace(namespaces: CommonNamespaceKeys[]): Namespace[];
4
- //# sourceMappingURL=hub.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hub.d.ts","sourceRoot":"","sources":["../../src/utils/hub.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2CAA2C,CAAC;AAE3E,wBAAgB,4CAA4C,CAC1D,UAAU,EAAE,mBAAmB,EAAE,GAChC,SAAS,EAAE,CAeb"}
@@ -1,26 +0,0 @@
1
- import type { QuoteUpdateWarning } from '../types';
2
-
3
- import { i18n } from '@lingui/core';
4
-
5
- import { QuoteUpdateType } from '../types';
6
-
7
- export function getQuoteUpdateWarningMessage(warning: QuoteUpdateWarning) {
8
- switch (warning.type) {
9
- case QuoteUpdateType.QUOTE_UPDATED:
10
- return i18n.t('Route has been updated.');
11
- case QuoteUpdateType.QUOTE_AND_OUTPUT_AMOUNT_UPDATED:
12
- return i18n.t(
13
- 'Output amount changed to {newOutputAmount} ({percentageChange}% change).',
14
- {
15
- newOutputAmount: warning.newOutputAmount,
16
- percentageChange: warning.percentageChange,
17
- }
18
- );
19
- case QuoteUpdateType.QUOTE_SWAPPERS_UPDATED:
20
- return i18n.t('Route swappers has been updated.');
21
- case QuoteUpdateType.QUOTE_COINS_UPDATED:
22
- return i18n.t('Route internal coins has been updated.');
23
- default:
24
- return '';
25
- }
26
- }