@imtbl/checkout-widgets 2.4.13 → 2.4.14-alpha.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 (41) hide show
  1. package/dist/browser/{AddTokensWidget-Dw62MGE7.js → AddTokensWidget-CF1YN2qr.js} +4 -4
  2. package/dist/browser/{BridgeWidget-pB9NQr0j.js → BridgeWidget-D1iYISBu.js} +6 -6
  3. package/dist/browser/{CommerceWidget-CmGjTT5f.js → CommerceWidget-0xlC0qeb.js} +13 -13
  4. package/dist/browser/{FeesBreakdown-D42F89mf.js → FeesBreakdown-9FvnOOCN.js} +1 -1
  5. package/dist/browser/{OnRampWidget-C11vbDpE.js → OnRampWidget-Db0Ma0JP.js} +3 -3
  6. package/dist/browser/{SaleWidget-C-kIuH_x.js → SaleWidget-BiU-JU_Y.js} +10 -10
  7. package/dist/browser/{SpendingCapHero-DxECFPhZ.js → SpendingCapHero-DoDWVXeM.js} +1 -1
  8. package/dist/browser/{SwapWidget-CaimjlZx.js → SwapWidget-0b44o7OG.js} +6 -6
  9. package/dist/browser/{TokenImage-CJcf0BVb.js → TokenImage-ON5CsElS.js} +1 -1
  10. package/dist/browser/{TopUpView-DIAfMQDk.js → TopUpView-BSsm_pag.js} +1 -1
  11. package/dist/browser/{WalletApproveHero-2qnl25R9.js → WalletApproveHero-BpQET2Ry.js} +2 -2
  12. package/dist/browser/{WalletWidget-EUpKwouL.js → WalletWidget-DPtHMDzk.js} +3 -3
  13. package/dist/browser/{auto-track-BLHegHT2.js → auto-track-YB97xHhP.js} +1 -1
  14. package/dist/browser/{index-BZQairfY.js → index-B6LlGDqn.js} +2 -2
  15. package/dist/browser/{index-B1kcsGhP.js → index-BGfRODL9.js} +1 -1
  16. package/dist/browser/{index-Co43S-f8.js → index-CYSUCb_r.js} +174 -192
  17. package/dist/browser/{index-C52OgfPn.js → index-CxVwwdjo.js} +1 -1
  18. package/dist/browser/{index-iCexzEAZ.js → index-DfqbSiW-.js} +1 -1
  19. package/dist/browser/{index-C7zLn4CO.js → index-DhJhrEPT.js} +1 -1
  20. package/dist/browser/{index-B6adB8ks.js → index-DkUaawBA.js} +1 -1
  21. package/dist/browser/{index-COIl8mga.js → index-_E9_8iXP.js} +1 -1
  22. package/dist/browser/index.js +1 -1
  23. package/dist/browser/{index.umd-ENtuIC6R.js → index.umd-C_C0lXQh.js} +1 -1
  24. package/dist/browser/{useInterval-BaXQ-Cl5.js → useInterval-BjJWflew.js} +1 -1
  25. package/dist/types/lib/squid/functions/execute.d.ts +8 -0
  26. package/dist/types/lib/squid/functions/routeCalculation.d.ts +22 -0
  27. package/dist/types/lib/squid/functions/slippage.d.ts +1 -0
  28. package/dist/types/lib/squid/hooks/useExecute.d.ts +1 -2
  29. package/dist/types/lib/squid/hooks/useRoutes.d.ts +1 -5
  30. package/package.json +7 -7
  31. package/src/lib/squid/functions/execute.ts +88 -0
  32. package/src/lib/squid/functions/routeCalculation.ts +162 -0
  33. package/src/lib/squid/functions/slippage.ts +36 -0
  34. package/src/lib/squid/hooks/useExecute.ts +3 -85
  35. package/src/lib/squid/hooks/useRoutes.ts +5 -115
  36. package/src/widgets/add-tokens/views/Review.tsx +2 -1
  37. package/src/widgets/purchase/views/Purchase.tsx +8 -2
  38. package/dist/types/lib/squid/hooks/useRouteCalculation.d.ts +0 -9
  39. package/dist/types/lib/squid/hooks/useSlippage.d.ts +0 -7
  40. package/src/lib/squid/hooks/useRouteCalculation.ts +0 -60
  41. package/src/lib/squid/hooks/useSlippage.ts +0 -45
@@ -3,7 +3,6 @@ import { RouteResponse, ActionType } from '@0xsquid/squid-types';
3
3
  import { Squid } from '@0xsquid/sdk';
4
4
  import { useRef } from 'react';
5
5
  import { formatUnits } from 'ethers';
6
- import { WrappedBrowserProvider } from '@imtbl/checkout-sdk';
7
6
  import { delay } from '../../../functions/delay';
8
7
  import { sortRoutesByFastestTime } from '../functions/sortRoutesByFastestTime';
9
8
  import { retry } from '../../retry';
@@ -14,12 +13,13 @@ import {
14
13
  } from '../types';
15
14
  import { SquidPostHook } from '../../primary-sales';
16
15
  import { SQUID_NATIVE_TOKEN } from '../config';
17
- import { findToken } from '../functions/findToken';
18
16
  import { isRouteToAmountGreaterThanToAmount } from '../functions/isRouteToAmountGreaterThanToAmount';
19
- import { useRouteCalculation } from './useRouteCalculation';
20
17
  import { RouteError } from '../RouteError';
21
-
22
- const INSUFFICIENT_GAS_THRESHOLD = 0.1;
18
+ import {
19
+ calculateFromAmountFromRoute,
20
+ convertToFormattedFromAmount,
21
+ getSufficientFromAmounts,
22
+ } from '../functions/routeCalculation';
23
23
 
24
24
  export const useRoutes = () => {
25
25
  const latestRequestIdRef = useRef<number>(0);
@@ -30,71 +30,6 @@ export const useRoutes = () => {
30
30
  },
31
31
  } = useProvidersContext();
32
32
 
33
- const { calculateFromAmount, calculateFromAmountFromRoute, convertToFormattedFromAmount } = useRouteCalculation();
34
-
35
- const getFromAmountData = (
36
- tokens: Token[],
37
- balance: TokenBalance,
38
- toAmount: string,
39
- toChainId: string,
40
- toTokenAddress: string,
41
- additionalBuffer: number = 0,
42
- ): FromAmountData | undefined => {
43
- const fromToken = findToken(
44
- tokens,
45
- balance.address,
46
- balance.chainId.toString(),
47
- );
48
- const toToken = findToken(tokens, toTokenAddress, toChainId);
49
-
50
- if (!fromToken || !toToken) {
51
- return undefined;
52
- }
53
-
54
- return {
55
- fromToken,
56
- fromAmount: calculateFromAmount(
57
- fromToken,
58
- toToken,
59
- toAmount,
60
- additionalBuffer,
61
- ),
62
- toToken,
63
- toAmount,
64
- balance,
65
- additionalBuffer,
66
- };
67
- };
68
-
69
- const getSufficientFromAmounts = (
70
- tokens: Token[],
71
- balances: TokenBalance[],
72
- toChainId: string,
73
- toTokenAddress: string,
74
- toAmount: string,
75
- ): FromAmountData[] => {
76
- const filteredBalances = balances.filter(
77
- (balance) => !(
78
- balance.address.toLowerCase() === toTokenAddress.toLowerCase()
79
- && balance.chainId === toChainId
80
- ),
81
- );
82
-
83
- const fromAmountDataArray: FromAmountData[] = filteredBalances
84
- .map((balance) => getFromAmountData(tokens, balance, toAmount, toChainId, toTokenAddress))
85
- .filter((value) => value !== undefined);
86
-
87
- return fromAmountDataArray.filter((data: FromAmountData) => {
88
- const formattedBalance = formatUnits(
89
- data.balance.balance,
90
- data.balance.decimals,
91
- );
92
- return (
93
- parseFloat(formattedBalance.toString()) > parseFloat(data.fromAmount)
94
- );
95
- });
96
- };
97
-
98
33
  const getRouteWithRetry = async (
99
34
  squid: Squid,
100
35
  fromToken: Token,
@@ -357,53 +292,8 @@ export const useRoutes = () => {
357
292
  }
358
293
  };
359
294
 
360
- const hasSufficientBalance = (
361
- balances: TokenBalance[],
362
- toTokenAddress: string,
363
- toChainId: string,
364
- toAmount: string,
365
- ): boolean => {
366
- const matchingTokens = balances.filter(
367
- (balance) => balance.address.toLowerCase() === toTokenAddress.toLowerCase()
368
- && balance.chainId.toString() === toChainId.toString(),
369
- );
370
-
371
- if (matchingTokens.length > 0) {
372
- return matchingTokens.some((balance) => {
373
- const tokenAmount = parseFloat(formatUnits(balance.balance, balance.decimals));
374
- return tokenAmount >= parseFloat(toAmount);
375
- });
376
- }
377
-
378
- return false;
379
- };
380
-
381
- const hasSufficientGas = (
382
- balances: TokenBalance[],
383
- selectedChainId: string | number,
384
- provider: WrappedBrowserProvider | undefined,
385
- ): boolean => {
386
- if (!provider) return false;
387
- if (isPassportProvider(provider)) return true;
388
-
389
- const nativeCurrencyBalance = balances.find(
390
- (balance) => balance.address.toLowerCase() === SQUID_NATIVE_TOKEN.toLowerCase()
391
- && balance.chainId.toString() === selectedChainId.toString(),
392
- );
393
- if (!nativeCurrencyBalance) return false;
394
-
395
- const nativeCurrencyBalanceAmount = parseFloat(
396
- formatUnits(nativeCurrencyBalance.balance, nativeCurrencyBalance.decimals),
397
- );
398
- if (nativeCurrencyBalanceAmount < INSUFFICIENT_GAS_THRESHOLD) return false;
399
- return true;
400
- };
401
-
402
295
  return {
403
- hasSufficientBalance,
404
- hasSufficientGas,
405
296
  fetchRoutes,
406
- getFromAmountData,
407
297
  getRoute,
408
298
  };
409
299
  };
@@ -66,6 +66,7 @@ import {
66
66
  } from '../AddTokensWidgetEvents';
67
67
  import { useErrorHandler } from '../hooks/useErrorHandler';
68
68
  import { AddTokensHandoverStep, useHandoverConfig } from '../hooks/useHandoverConfig';
69
+ import { getFromAmountData } from '../../../lib/squid/functions/routeCalculation';
69
70
 
70
71
  interface ReviewProps {
71
72
  data: AddTokensReviewData;
@@ -116,7 +117,7 @@ export function Review({
116
117
  const [showFeeBreakdown, setShowFeeBreakdown] = useState(false);
117
118
  const [showSecuringQuote, setShowSecuringQuote] = useState(false);
118
119
  const [showAddressMissmatchDrawer, setShowAddressMissmatchDrawer] = useState(false);
119
- const { getFromAmountData, getRoute } = useRoutes();
120
+ const { getRoute } = useRoutes();
120
121
  const { showHandover } = useHandoverConfig(checkout.config.environment);
121
122
 
122
123
  const { onTransactionError } = useErrorHandler();
@@ -46,6 +46,12 @@ import {
46
46
  } from '../types';
47
47
  import { ViewActions, ViewContext } from '../../../context/view-context/ViewContext';
48
48
  import { PurchaseWidgetViews } from '../../../context/view-context/PurchaseViewContextTypes';
49
+ import {
50
+ getFromAmountData,
51
+ hasSufficientBalance,
52
+ hasSufficientGas,
53
+ } from '../../../lib/squid/functions/routeCalculation';
54
+ import { waitForReceipt } from '../../../lib/squid/functions/execute';
49
55
 
50
56
  interface PurchaseProps {
51
57
  checkout: Checkout;
@@ -109,12 +115,12 @@ export function Purchase({
109
115
  } = useProvidersContext();
110
116
 
111
117
  const {
112
- fetchRoutes, getRoute, getFromAmountData, hasSufficientBalance, hasSufficientGas,
118
+ fetchRoutes, getRoute,
113
119
  } = useRoutes();
114
120
  const { providers } = useInjectedProviders({ checkout });
115
121
 
116
122
  const {
117
- getAllowance, approve, execute, getStatus, waitForReceipt,
123
+ getAllowance, approve, execute, getStatus,
118
124
  } = useExecute(UserJourney.PURCHASE, (err) => {
119
125
  // eslint-disable-next-line no-console
120
126
  console.log('useExecute err', err);
@@ -1,9 +0,0 @@
1
- import { Token } from '../types';
2
- /**
3
- * Hook to handle route amount calculations.
4
- */
5
- export declare const useRouteCalculation: () => {
6
- calculateFromAmount: (fromToken: Token, toToken: Token, toAmount: string, additionalBuffer?: number) => string;
7
- calculateFromAmountFromRoute: (exchangeRate: string, toAmount: string, toAmountUSD?: string) => string;
8
- convertToFormattedFromAmount: (amount: string, decimals: number) => string;
9
- };
@@ -1,7 +0,0 @@
1
- /**
2
- * Hook to calculate slippage based on thresholds
3
- */
4
- export declare const useSlippage: () => {
5
- getSlippageTier: (usdAmount: number) => number;
6
- calculateAdjustedAmount: (baseAmount: number, usdAmount: number, additionalBuffer?: number) => number;
7
- };
@@ -1,60 +0,0 @@
1
- import { useMemo } from 'react';
2
- import { parseUnits } from 'ethers';
3
- import { useSlippage } from './useSlippage';
4
- import { Token } from '../types';
5
-
6
- /**
7
- * Hook to handle route amount calculations.
8
- */
9
- export const useRouteCalculation = () => {
10
- const { calculateAdjustedAmount } = useSlippage();
11
-
12
- /**
13
- * Calculate the fromAmount based on USD prices and slippage.
14
- */
15
- const calculateFromAmount = (
16
- fromToken: Token,
17
- toToken: Token,
18
- toAmount: string,
19
- additionalBuffer: number = 0,
20
- ) => {
21
- const toAmountNumber = parseFloat(toAmount);
22
- // Calculate the USD value of the toAmount
23
- const toAmountInUsd = toAmountNumber * toToken.usdPrice;
24
- // Calculate the amount of fromToken needed to match this USD value
25
- const baseFromAmount = toAmountInUsd / fromToken.usdPrice;
26
- // Add a buffer for price fluctuations and fees
27
- const fromAmountWithBuffer = calculateAdjustedAmount(baseFromAmount, toAmountInUsd, additionalBuffer);
28
-
29
- return fromAmountWithBuffer.toString();
30
- };
31
-
32
- /**
33
- * Calculate the fromAmount using exchange rate returned from the route.
34
- */
35
- const calculateFromAmountFromRoute = (
36
- exchangeRate: string,
37
- toAmount: string,
38
- toAmountUSD?: string,
39
- ) => {
40
- const toAmountUSDNumber = toAmountUSD ? parseFloat(toAmountUSD) : 0;
41
- const fromAmount = parseFloat(toAmount) / parseFloat(exchangeRate);
42
- const fromAmountWithBuffer = calculateAdjustedAmount(fromAmount, toAmountUSDNumber);
43
- return fromAmountWithBuffer.toString();
44
- };
45
-
46
- /**
47
- * Convert a string amount to a formatted amount with the specified number of decimals.
48
- */
49
- const convertToFormattedFromAmount = (amount: string, decimals: number) => {
50
- const parsedFromAmount = parseFloat(amount).toFixed(decimals);
51
- const formattedFromAmount = parseUnits(parsedFromAmount, decimals);
52
- return formattedFromAmount.toString();
53
- };
54
-
55
- return useMemo(() => ({
56
- calculateFromAmount,
57
- calculateFromAmountFromRoute,
58
- convertToFormattedFromAmount,
59
- }), []);
60
- };
@@ -1,45 +0,0 @@
1
- import { useMemo } from 'react';
2
-
3
- const BASE_SLIPPAGE_HIGH_TIER = 0.005;
4
- const BASE_SLIPPAGE_MEDIUM_TIER = 0.01;
5
- const BASE_SLIPPAGE_LOW_TIER = 0.015;
6
-
7
- const SLIPPAGE_TIERS = {
8
- high: {
9
- threshold: 999,
10
- value: BASE_SLIPPAGE_HIGH_TIER,
11
- },
12
- medium: {
13
- threshold: 99,
14
- value: BASE_SLIPPAGE_MEDIUM_TIER,
15
- },
16
- low: {
17
- threshold: 0,
18
- value: BASE_SLIPPAGE_LOW_TIER,
19
- },
20
- } as const;
21
-
22
- /**
23
- * Hook to calculate slippage based on thresholds
24
- */
25
- export const useSlippage = () => {
26
- const getSlippageTier = (usdAmount: number): number => {
27
- if (usdAmount >= SLIPPAGE_TIERS.high.threshold) return SLIPPAGE_TIERS.high.value;
28
- if (usdAmount >= SLIPPAGE_TIERS.medium.threshold) return SLIPPAGE_TIERS.medium.value;
29
- return SLIPPAGE_TIERS.low.value;
30
- };
31
-
32
- const calculateAdjustedAmount = (
33
- baseAmount: number,
34
- usdAmount: number,
35
- additionalBuffer: number = 0,
36
- ): number => {
37
- const slippage = getSlippageTier(usdAmount);
38
- return baseAmount * (1 + slippage + additionalBuffer);
39
- };
40
-
41
- return useMemo(() => ({
42
- getSlippageTier,
43
- calculateAdjustedAmount,
44
- }), []);
45
- };