@rango-dev/widget-embedded 0.1.10-next.76 → 0.1.10-next.80

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.
@@ -8,7 +8,7 @@ import BigNumber, { BigNumber as BigNumber$1 } from 'bignumber.js';
8
8
  import { RangoClient, TransactionType } from 'rango-sdk';
9
9
  import { readAccountAddress, useWallets, Provider, Events } from '@rango-dev/wallets-core';
10
10
  import { allProviders } from '@rango-dev/provider-all';
11
- import { Network, isEvmAddress, WalletType, isEvmBlockchain } from '@rango-dev/wallets-shared';
11
+ import { Network, isEvmAddress, KEPLR_COMPATIBLE_WALLETS, WalletType, getCosmosExperimentalChainInfo, isCosmosBlockchain, isEvmBlockchain } from '@rango-dev/wallets-shared';
12
12
  import { persist } from 'zustand/middleware';
13
13
  import { styled as styled$1 } from '@rango-dev/ui/src/theme';
14
14
 
@@ -375,10 +375,11 @@ function getSelectableWallets(accounts, selectedWallets, getWalletInfo, required
375
375
  name: getWalletInfo(account.walletType).name,
376
376
  selected: !!selectedWallets.find(wallet => wallet.chain === account.chain && wallet.walletType === account.walletType)
377
377
  }));
378
- return requiredChains ? connectedWallets.filter(wallet => requiredChains.includes(wallet.chain)) : removeDuplicateWallets(connectedWallets, 'walletType');
378
+ return requiredChains ? connectedWallets.filter((wallet, index, array) => requiredChains.includes(wallet.chain) && array.findIndex(w => w.address === wallet.address) === index) : removeDuplicateWallets(connectedWallets, 'walletType');
379
379
  }
380
380
  const removeDuplicateWallets = (arr, key) => {
381
- return [...new Map(arr.map(item => [item[key], item])).values()];
381
+ const map = new Map(arr.map(item => [item[key], item]));
382
+ return Array.from(map.values());
382
383
  };
383
384
  function getBalanceFromWallet(balances, chain, symbol, address) {
384
385
  if (balances.length === 0) return null;
@@ -442,8 +443,6 @@ const calculateWalletUsdValue = balance => {
442
443
  return modifiedWalletBlockchain;
443
444
  });
444
445
  const total = numberToString(modifiedWalletBlockchains?.flatMap(b => b.accounts)?.flatMap(a => a?.balances)?.map(b => new BigNumber(b?.amount || ZERO).multipliedBy(b?.usdPrice || 0))?.reduce((a, b) => a.plus(b), ZERO) || ZERO).toString();
445
- console.log('total');
446
- console.log(total);
447
446
  return numberWithThousandSeperator(total);
448
447
  };
449
448
  function numberWithThousandSeperator(number) {
@@ -468,6 +467,17 @@ const getUsdPrice = (blockchain, symbol, address, allTokens) => {
468
467
  const token = allTokens?.find(t => t.blockchain === blockchain && t.symbol?.toUpperCase() === symbol?.toUpperCase() && t.address === address);
469
468
  return token?.usdPrice || null;
470
469
  };
470
+ const isExperimentalChain = (blockchains, wallet) => {
471
+ const cosmosExperimentalChainInfo = getCosmosExperimentalChainInfo(Object.entries(blockchains).map(_ref => {
472
+ let [, blockchainMeta] = _ref;
473
+ return blockchainMeta;
474
+ }).filter(isCosmosBlockchain));
475
+ return cosmosExperimentalChainInfo && !!cosmosExperimentalChainInfo[wallet];
476
+ };
477
+ const getKeplrCompatibleConnectedWallets = selectableWallets => {
478
+ const connectedWalletTypes = new Set(selectableWallets.map(a => a.walletType.toString()));
479
+ return KEPLR_COMPATIBLE_WALLETS.filter(compatibleWallet => connectedWalletTypes.has(compatibleWallet));
480
+ };
471
481
 
472
482
  const useWalletsStore = /*#__PURE__*/createSelectors( /*#__PURE__*/create()(set => ({
473
483
  accounts: [],
@@ -596,111 +606,7 @@ const useSettingsStore = /*#__PURE__*/createSelectors( /*#__PURE__*/create()( /*
596
606
  name: 'user-settings'
597
607
  })));
598
608
 
599
- function getOutputRatio(inputUsdValue, outputUsdValue) {
600
- if (inputUsdValue.lte(ZERO) || outputUsdValue.lte(ZERO)) return 0;
601
- return outputUsdValue.div(inputUsdValue).minus(1).multipliedBy(100);
602
- }
603
- function outputRatioHasWarning(inputUsdValue, outputRatio) {
604
- return parseInt(outputRatio.toFixed(2) || '0') <= -10 && inputUsdValue.gte(new BigNumber(400)) || parseInt(outputRatio.toFixed(2) || '0') <= -5 && inputUsdValue.gte(new BigNumber(1000));
605
- }
606
- function hasLimitError(bestRoute) {
607
- return (bestRoute?.result?.swaps || []).filter(swap => {
608
- const minimum = !!swap.fromAmountMinValue ? new BigNumber(swap.fromAmountMinValue) : null;
609
- const maximum = !!swap.fromAmountMaxValue ? new BigNumber(swap.fromAmountMaxValue) : null;
610
- const isExclusive = swap.fromAmountRestrictionType === 'EXCLUSIVE';
611
- if (isExclusive) {
612
- return minimum?.gte(swap.fromAmount) || maximum?.lte(swap.fromAmount);
613
- } else {
614
- return minimum?.gt(swap.fromAmount) || maximum?.lt(swap.fromAmount);
615
- }
616
- }).length > 0;
617
- }
618
- function getSwapButtonTitle(accounts, loading, hasLimitError, highValueLoss, priceImpactCanNotBeComputed, needsToWarnEthOnPath) {
619
- if (loading) return 'Finding Best Route...';
620
- if (accounts.length == 0) return 'Connect Wallet';else if (hasLimitError) return 'Limit Error';else if (highValueLoss) return 'Price impact is too high!';else if (priceImpactCanNotBeComputed) return 'USD price is unknown, price impact might be high!';else if (needsToWarnEthOnPath) return 'The route goes through Ethereum. Continue?';else return 'Swap';
621
- }
622
- function canComputePriceImpact(bestRoute, inputAmount, inputUsdValue, outputUsdValue) {
623
- return !((inputUsdValue.lte(ZERO) || outputUsdValue.lte(ZERO)) && !!bestRoute?.result && !!inputAmount && inputAmount !== '0' && parseFloat(inputAmount || '0') !== 0);
624
- }
625
- function calculatePendingSwap(inputAmount, bestRoute, wallets, settings, validateBalanceOrFee) {
626
- const simulationResult = bestRoute.result;
627
- if (!simulationResult) throw Error('Simulation result should not be null');
628
- return {
629
- creationTime: new Date().getTime().toString(),
630
- finishTime: null,
631
- requestId: bestRoute.requestId || '',
632
- inputAmount: inputAmount,
633
- wallets,
634
- status: 'running',
635
- isPaused: false,
636
- extraMessage: null,
637
- extraMessageSeverity: null,
638
- extraMessageDetail: null,
639
- extraMessageErrorCode: null,
640
- networkStatusExtraMessage: null,
641
- networkStatusExtraMessageDetail: null,
642
- lastNotificationTime: null,
643
- settings: settings,
644
- simulationResult: simulationResult,
645
- validateBalanceOrFee,
646
- //TODO: finalize PendingSwap type and remove ts-ignore
647
- //@ts-ignore
648
- steps: bestRoute.result?.swaps?.map((s, i) => ({
649
- id: i + 1,
650
- fromBlockchain: s.from.blockchain,
651
- fromSymbol: s.from.symbol,
652
- fromSymbolAddress: s.from.address,
653
- fromDecimals: s.from.decimals,
654
- fromAmountPrecision: s.fromAmountPrecision,
655
- fromAmountMinValue: s.fromAmountMinValue,
656
- fromAmountMaxValue: s.fromAmountMaxValue,
657
- toBlockchain: s.to.blockchain,
658
- fromLogo: s.from.logo,
659
- toSymbol: s.to.symbol,
660
- toSymbolAddress: s.to.address,
661
- toDecimals: s.to.decimals,
662
- toLogo: s.to.logo,
663
- startTransactionTime: new Date().getTime(),
664
- swapperId: s.swapperId,
665
- expectedOutputAmountHumanReadable: s.toAmount,
666
- outputAmount: null,
667
- status: 'created',
668
- networkStatus: null,
669
- executedTransactionId: null,
670
- externalTransactionId: null,
671
- explorerUrl: null,
672
- trackingCode: null,
673
- cosmosTransaction: null,
674
- solanaTransaction: null,
675
- starknetTransaction: null,
676
- starknetApprovalTransaction: null,
677
- tronTransaction: null,
678
- tronApprovalTransaction: null,
679
- evmTransaction: null,
680
- evmApprovalTransaction: null,
681
- transferTransaction: null,
682
- diagnosisUrl: null,
683
- internalSteps: null,
684
- fromBlockchainLogo: '',
685
- toBlockchainLogo: '',
686
- swapperLogo: '',
687
- swapperType: ''
688
- })) || []
689
- };
690
- }
691
- function requiredWallets(route) {
692
- const wallets = [];
693
- route?.result?.swaps.forEach(swap => {
694
- const currentStepFromBlockchain = swap.from.blockchain;
695
- const currentStepToBlockchain = swap.to.blockchain;
696
- let lastAddedWallet = wallets[wallets.length - 1];
697
- if (currentStepFromBlockchain != lastAddedWallet) wallets.push(currentStepFromBlockchain);
698
- lastAddedWallet = wallets[wallets.length - 1];
699
- if (currentStepToBlockchain != lastAddedWallet) wallets.push(currentStepToBlockchain);
700
- });
701
- return wallets;
702
- }
703
-
609
+ // import { WalletType } from '@rango-dev/wallets-shared';
704
610
  function useConfirmSwap() {
705
611
  const fromToken = useBestRouteStore.use.fromToken();
706
612
  const toToken = useBestRouteStore.use.toToken();
@@ -802,6 +708,7 @@ function useConfirmSwap() {
802
708
  const routeChangeStatus = compareRoutes(bestRoute, r, inputAmount.toString(), fromToken.usdPrice, toToken.usdPrice);
803
709
  setBestRoute(r);
804
710
  const isChanged = routeChangeStatus.isChanged;
711
+ // const changeWarningMessage = routeChangeStatus.warningMessage;
805
712
  setBestRouteChanged(isChanged);
806
713
  setWarning('Best route changed');
807
714
  setData(r);
@@ -813,19 +720,34 @@ function useConfirmSwap() {
813
720
  const swap = () => {
814
721
  if (!bestRoute) return;
815
722
  if (inputAmount.toString() === '') return;
816
- const wallets = selectedWallets.reduce((selectedWalletsMap, selectedWallet) => (selectedWalletsMap[selectedWallet.chain] = {
817
- address: selectedWallet.address,
818
- walletType: selectedWallet.walletType
819
- }, selectedWalletsMap), {});
723
+ // const wallets = selectedWallets.reduce(
724
+ // (
725
+ // selectedWalletsMap: { [p: string]: { address: string; walletType: WalletType } },
726
+ // selectedWallet,
727
+ // ) => (
728
+ // (selectedWalletsMap[selectedWallet.chain] = {
729
+ // address: selectedWallet.address,
730
+ // walletType: selectedWallet.walletType,
731
+ // }),
732
+ // selectedWalletsMap
733
+ // ),
734
+ // {},
735
+ // );
820
736
  const proceedAnyway = enoughBalance !== null;
821
- const settings = {
822
- slippage: slippage.toString(),
823
- disabledSwappersGroups: ['Osmosis'],
824
- disabledSwappersIds: []
825
- };
826
- if (proceedAnyway) {
827
- const newSwap = calculatePendingSwap(inputAmount.toString(), bestRoute, wallets, settings, false);
828
- }
737
+ // const settings: SwapSavedSettings = {
738
+ // slippage: slippage.toString(),
739
+ // disabledSwappersGroups: ['Osmosis'],
740
+ // disabledSwappersIds: [],
741
+ // };
742
+ // if (proceedAnyway) {
743
+ // const newSwap: PendingSwap = calculatePendingSwap(
744
+ // inputAmount!.toString(),
745
+ // bestRoute,
746
+ // wallets,
747
+ // settings,
748
+ // false,
749
+ // );
750
+ // }
829
751
  !proceedAnyway && checkFeeAndBalance(selectedWallets).then(data => {
830
752
  if (!data) {
831
753
  setError('confirm swap error');
@@ -835,17 +757,15 @@ function useConfirmSwap() {
835
757
  setError('confirm swap error');
836
758
  return;
837
759
  } else {
760
+ // @ts-ignore
838
761
  const {
839
- hasEnoughBalanceOrSlippage,
840
- bestRoute: newBestRoute
762
+ hasEnoughBalanceOrSlippage
841
763
  } = data;
842
764
  if (!hasEnoughBalanceOrSlippage) {
843
765
  return;
844
766
  }
845
767
  setEnoughBalance(hasEnoughBalanceOrSlippage.balance && hasEnoughBalanceOrSlippage.slippage);
846
- if (hasEnoughBalanceOrSlippage.balance && hasEnoughBalanceOrSlippage.slippage && !hasEnoughBalanceOrSlippage.routeChanged) {
847
- const newSwap = calculatePendingSwap(inputAmount.toString(), newBestRoute, wallets, settings, true);
848
- } else if (!hasEnoughBalanceOrSlippage.balance) {
768
+ if (hasEnoughBalanceOrSlippage.balance && hasEnoughBalanceOrSlippage.slippage && !hasEnoughBalanceOrSlippage.routeChanged) ; else if (!hasEnoughBalanceOrSlippage.balance) {
849
769
  setError('not enough balance');
850
770
  }
851
771
  }
@@ -1875,6 +1795,45 @@ const errorMessages = {
1875
1795
  genericServerError: 'Error connecting server, please reload the app and try again'
1876
1796
  };
1877
1797
 
1798
+ function getOutputRatio(inputUsdValue, outputUsdValue) {
1799
+ if (inputUsdValue.lte(ZERO) || outputUsdValue.lte(ZERO)) return 0;
1800
+ return outputUsdValue.div(inputUsdValue).minus(1).multipliedBy(100);
1801
+ }
1802
+ function outputRatioHasWarning(inputUsdValue, outputRatio) {
1803
+ return parseInt(outputRatio.toFixed(2) || '0') <= -10 && inputUsdValue.gte(new BigNumber(400)) || parseInt(outputRatio.toFixed(2) || '0') <= -5 && inputUsdValue.gte(new BigNumber(1000));
1804
+ }
1805
+ function hasLimitError(bestRoute) {
1806
+ return (bestRoute?.result?.swaps || []).filter(swap => {
1807
+ const minimum = !!swap.fromAmountMinValue ? new BigNumber(swap.fromAmountMinValue) : null;
1808
+ const maximum = !!swap.fromAmountMaxValue ? new BigNumber(swap.fromAmountMaxValue) : null;
1809
+ const isExclusive = swap.fromAmountRestrictionType === 'EXCLUSIVE';
1810
+ if (isExclusive) {
1811
+ return minimum?.gte(swap.fromAmount) || maximum?.lte(swap.fromAmount);
1812
+ } else {
1813
+ return minimum?.gt(swap.fromAmount) || maximum?.lt(swap.fromAmount);
1814
+ }
1815
+ }).length > 0;
1816
+ }
1817
+ function getSwapButtonTitle(accounts, loading, hasLimitError, highValueLoss, priceImpactCanNotBeComputed, needsToWarnEthOnPath) {
1818
+ if (loading) return 'Finding Best Route...';
1819
+ if (accounts.length == 0) return 'Connect Wallet';else if (hasLimitError) return 'Limit Error';else if (highValueLoss) return 'Price impact is too high!';else if (priceImpactCanNotBeComputed) return 'USD price is unknown, price impact might be high!';else if (needsToWarnEthOnPath) return 'The route goes through Ethereum. Continue?';else return 'Swap';
1820
+ }
1821
+ function canComputePriceImpact(bestRoute, inputAmount, inputUsdValue, outputUsdValue) {
1822
+ return !((inputUsdValue.lte(ZERO) || outputUsdValue.lte(ZERO)) && !!bestRoute?.result && !!inputAmount && inputAmount !== '0' && parseFloat(inputAmount || '0') !== 0);
1823
+ }
1824
+ function requiredWallets(route) {
1825
+ const wallets = [];
1826
+ route?.result?.swaps.forEach(swap => {
1827
+ const currentStepFromBlockchain = swap.from.blockchain;
1828
+ const currentStepToBlockchain = swap.to.blockchain;
1829
+ let lastAddedWallet = wallets[wallets.length - 1];
1830
+ if (currentStepFromBlockchain != lastAddedWallet) wallets.push(currentStepFromBlockchain);
1831
+ lastAddedWallet = wallets[wallets.length - 1];
1832
+ if (currentStepToBlockchain != lastAddedWallet) wallets.push(currentStepToBlockchain);
1833
+ });
1834
+ return wallets;
1835
+ }
1836
+
1878
1837
  const Container$2 = /*#__PURE__*/styled('div', {
1879
1838
  display: 'flex',
1880
1839
  flexDirection: 'column',
@@ -2153,7 +2112,8 @@ const ListContainer = /*#__PURE__*/styled('div', {
2153
2112
  gap: '.5rem',
2154
2113
  gridTemplateColumns: ' repeat(2, minmax(0, 1fr))',
2155
2114
  height: '450px',
2156
- alignContent: 'baseline'
2115
+ alignContent: 'baseline',
2116
+ padding: '0 0.5rem'
2157
2117
  });
2158
2118
  const AlertContainer = /*#__PURE__*/styled('div', {
2159
2119
  paddingBottom: '$16'
@@ -2200,25 +2160,36 @@ function WalletsPage() {
2200
2160
  function ConfirmWalletsPage() {
2201
2161
  const navigate = useNavigate();
2202
2162
  const bestRoute = useBestRouteStore.use.bestRoute();
2163
+ const {
2164
+ blockchains
2165
+ } = useMetaStore.use.meta();
2203
2166
  const accounts = useWalletsStore.use.accounts();
2204
2167
  const selectedWallets = useWalletsStore.use.selectedWallets();
2205
2168
  const initSelectedWallets = useWalletsStore.use.initSelectedWallets();
2206
2169
  const setSelectedWallet = useWalletsStore.use.setSelectedWallet();
2207
2170
  const {
2208
- getWalletInfo
2171
+ getWalletInfo,
2172
+ connect
2209
2173
  } = useWallets();
2210
2174
  const confirmDisabled = !requiredWallets(bestRoute).every(chain => selectedWallets.map(wallet => wallet.chain).includes(chain));
2211
2175
  useEffect(() => {
2212
2176
  initSelectedWallets();
2213
2177
  }, []);
2178
+ const selectableWallets = getSelectableWallets(accounts, selectedWallets, getWalletInfo, getRequiredChains(bestRoute));
2179
+ const handleConnectChain = wallet => {
2180
+ const network = wallet;
2181
+ getKeplrCompatibleConnectedWallets(selectableWallets).forEach(compatibleWallet => connect?.(compatibleWallet, network));
2182
+ };
2214
2183
  return React.createElement(ConfirmWallets, {
2215
2184
  requiredWallets: getRequiredChains(bestRoute),
2216
- selectableWallets: getSelectableWallets(accounts, selectedWallets, getWalletInfo, getRequiredChains(bestRoute)),
2185
+ selectableWallets: selectableWallets,
2217
2186
  onBack: () => navigate(-1),
2218
2187
  swap: bestRoute,
2219
2188
  onConfirm: () => navigate(navigationRoutes.confirmSwap),
2220
2189
  onChange: wallet => setSelectedWallet(wallet),
2221
- confirmDisabled: confirmDisabled
2190
+ confirmDisabled: confirmDisabled,
2191
+ handleConnectChain: wallet => handleConnectChain(wallet),
2192
+ isExperimentalChain: wallet => getKeplrCompatibleConnectedWallets(selectableWallets).length > 0 ? isExperimentalChain(blockchains, wallet) : false
2222
2193
  });
2223
2194
  }
2224
2195