@rash2x/bridge-widget 0.7.9 → 0.8.1

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.
@@ -52,7 +52,7 @@ const en$3 = {
52
52
  };
53
53
  const common = { "connecting": "Подключение…", "initializing": "Инициализация...", "loading": "Загрузка...", "paste": "вставить", "close": "Закрыть", "zeroPlaceholder": "0", "nativeToken": "Нативный токен" };
54
54
  const wallets = { "addTonWallet": "Добавить TON кошелёк", "addEvmWallet": "Добавить EVM кошелёк", "connectTonWallet": "Подключить TON кошелёк", "connectEvmWallet": "Подключить EVM кошелёк", "initializingMetamask": "Инициализация MetaMask SDK...", "initializingTronlink": "Инициализация TronLink...", "failedToConnectTon": "Не удалось подключиться к TON кошельку", "failedToDisconnect": "Не удалось отключиться", "metamaskConnectionError": "Ошибка подключения MetaMask", "failedToConnectMetamask": "Не удалось подключиться к MetaMask", "failedToDisconnectMetamask": "Не удалось отключиться от MetaMask", "selectWallet": "Выберите кошелёк", "tonWallets": "TON", "evmWallets": "EVM", "tronWallets": "TRON", "tonconnect": "TonConnect", "metaMask": "WalletConnect", "walletConnect": "WalletConnect", "tronLink": "TronLink", "addTronWallet": "Добавить Tron кошелёк", "comingSoon": "Скоро", "connected": "ПОДКЛЮЧЕНО", "connectedStatus": "Подключён", "disconnect": "Отключить", "chooseWallet": "Подключите кошелек", "oneWalletPerEnv": "Можно подключить только один кошелёк на окружение.", "connect": "Подключить", "connectTronWallet": "Подключить Tron кошелёк", "connectWallet": "Подключить кошелёк" };
55
- const bridge = { "max": "Макс", "sourceNetwork": "Исходная сеть", "destinationNetwork": "Целевая сеть", "selectToken": "Выбрать токен", "selectNetwork": "Выбрать сеть", "selectSourceNetwork": "Выбрать исходную сеть", "selectDestinationNetwork": "Выбрать целевую сеть", "searchToken": "Поиск токена", "myTokens": "Мои токены", "allTokens": "Все токены", "search": "Поиск", "select": "Выбрать", "willChangeSourceChain": "Сменит исходную сеть", "willChangeDestinationChain": "Сменит целевую сеть", "willChangeBothChains": "Сменит обе сети", "willChangeSourceNetworkAndToken": "Сменит исходный токен", "noBalancesFound": "Балансы не найдены.", "noResults": "Нет результатов", "tokenNotFound": "Мы не смогли найти токен с таким названием или символом. Пожалуйста, попробуйте снова.", "chainNotFound": "Мы не смогли найти сеть с таким названием. Пожалуйста, попробуйте снова.", "sendToAnotherAddress": "Отправить на другой адрес", "youWillReceive": "Вы получите", "anotherAddressPlaceholder": "Адрес", "addressDoesntMatch": "Адрес не соответствует сети {{network}}", "checkBeforeTransfer": "Проверьте корректность перед переводом" };
55
+ const bridge = { "max": "Макс", "sourceNetwork": "Исходная сеть", "destinationNetwork": "Целевая сеть", "selectToken": "Выбрать токен", "selectNetwork": "Выбрать сеть", "selectSourceNetwork": "Выберите Исходную сеть", "selectDestinationNetwork": "Выберите Целевую сеть", "searchToken": "Поиск токена", "myTokens": "Мои токены", "allTokens": "Все токены", "search": "Поиск", "select": "Выбрать", "willChangeSourceChain": "Сменит исходную сеть", "willChangeDestinationChain": "Сменит целевую сеть", "willChangeBothChains": "Сменит обе сети", "willChangeSourceNetworkAndToken": "Сменит исходный токен", "noBalancesFound": "Балансы не найдены.", "noResults": "Нет результатов", "tokenNotFound": "Мы не смогли найти токен с таким названием или символом. Пожалуйста, попробуйте снова.", "chainNotFound": "Мы не смогли найти сеть с таким названием. Пожалуйста, попробуйте снова.", "sendToAnotherAddress": "Отправить на другой адрес", "youWillReceive": "Вы получите", "anotherAddressPlaceholder": "Адрес", "addressDoesntMatch": "Адрес не соответствует сети {{network}}", "checkBeforeTransfer": "Проверьте корректность перед переводом" };
56
56
  const transaction = { "enterAmount": "Введите сумму", "transfer": "Перевести", "getQuote": "Получить котировку", "quoting": "Расчет котировки...", "failed": "Ошибка транзакции", "confirm": "Подтвердите транзакцию", "signTransaction": "Подпишите транзакцию в кошельке", "inProgress": "Транзакция выполняется...", "checkingBalance": "Проверка баланса...", "insufficientBalance": "Недостаточно средств", "amountTooSmall": "Минимум {{min}}", "amountTooLarge": "Максимум {{max}}", "success": "Успех", "successTitle": "Успех", "done": "Готово", "hashCopied": "Хэш скопирован в буфер обмена", "bridged": "Переведено", "transferTitle": "Перевод", "hash": "Хэш", "layerzeroScan": "TxHash", "finalFee": "Итоговая комиссия", "route": "Маршрут", "routeTooltip": "Маршрут — это путь, по которому будет выполнен перевод. Мост работает на базе LayerZero, а конкретный путь передачи между сетями может влиять на комиссию, проскальзывание и время.", "estTime": "Время", "estTimeTooltip": "Среднее время — примерное время завершения перевода. Зависит от маршрута и нагрузки сети; фактическое время может отличаться.", "slippage": "Проскальзывание", "slippageTooltip": "Если получаемая сумма окажется ниже этого допуска, транзакция будет отклонена.", "minimumReceived": "Минимум к получению", "messageFee": "Комиссия сообщения", "messageFeeTooltip": "Комиссия сообщения — стоимость кросс-чейн передачи через LayerZero для ретрансляции транзакции между сетями.", "bridgeFee": "Комиссия моста", "bridgeFeeTooltip": "Комиссия моста — разница между отправленной и полученной суммой, взимаемая протоколом моста.", "totalFee": "Общая комиссия", "totalFeeTooltip": "Общая комиссия за перевод, включая комиссию сообщения и моста. Фактическая сумма может немного измениться.", "gasEstimate": "Газ: {{gas}}", "noRouteFound": "Маршрут не найден", "noRouteAlert": "Маршрут не найден. Выберите другую сеть отправления или получения.", "notEnoughGas": "Недостаточно газа", "pasteAddressToTransfer": "Укажите адрес получателя", "noRouteFoundForSettings": "Маршрут не найден для текущих настроек.", "tryAdjustSettings": "Попробуйте отключить Gas on Destination или измените сумму/сети.", "quoteError": "Ошибка котировки", "steps": { "sent": "Отправлено", "approving": "Одобрение токена", "approvingNote": "Шаг {{current}} из {{total}}: Подтвердите одобрение в кошельке", "bridging": "Перевод через мост", "processing": "Обработка", "processingNote": "До 2 минут", "completed": "Завершено" } };
57
57
  const telegram = { "openWebVersion": "Открыть EVAA веб для трансфера", "restrictionMessage": "Трансфер между выбранными сетями доступен только в веб-версии EVAA" };
58
58
  const app = { "stargateWidgetName": "Виджет Stargate Bridge", "liveWidget": "Живой виджет", "getStarted": "Начало работы" };
@@ -1469,8 +1469,10 @@ function useChainStrategies() {
1469
1469
  const useWalletSelectModal = create((set2) => ({
1470
1470
  isOpen: false,
1471
1471
  addressType: void 0,
1472
- onOpen: (addressType) => set2({ isOpen: true, addressType }),
1473
- onClose: () => set2({ isOpen: false, addressType: void 0 })
1472
+ lastConnectionAddressType: void 0,
1473
+ onOpen: (addressType) => set2({ isOpen: true, addressType, lastConnectionAddressType: addressType }),
1474
+ onClose: () => set2({ isOpen: false, addressType: void 0 }),
1475
+ setLastConnectionAddressType: (addressType) => set2({ lastConnectionAddressType: addressType })
1474
1476
  }));
1475
1477
  const truncateToDecimals = (num, decimals) => {
1476
1478
  if (!isFinite(num) || isNaN(num)) return "0";
@@ -5019,6 +5021,197 @@ function getTonClient(customClient, apiKey) {
5019
5021
  }
5020
5022
  return tonClientInstance;
5021
5023
  }
5024
+ const NETWORK_CONFIGS = {
5025
+ 1: {
5026
+ chainId: "0x1",
5027
+ chainName: "Ethereum Mainnet",
5028
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5029
+ rpcUrls: ["https://eth.llamarpc.com"],
5030
+ blockExplorerUrls: ["https://etherscan.io"]
5031
+ },
5032
+ 42161: {
5033
+ chainId: "0xa4b1",
5034
+ chainName: "Arbitrum One",
5035
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5036
+ rpcUrls: ["https://arbitrum.llamarpc.com"],
5037
+ blockExplorerUrls: ["https://arbiscan.io"]
5038
+ },
5039
+ 10: {
5040
+ chainId: "0xa",
5041
+ chainName: "Optimism",
5042
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5043
+ rpcUrls: ["https://optimism.llamarpc.com"],
5044
+ blockExplorerUrls: ["https://optimistic.etherscan.io"]
5045
+ },
5046
+ 137: {
5047
+ chainId: "0x89",
5048
+ chainName: "Polygon",
5049
+ nativeCurrency: { name: "MATIC", symbol: "MATIC", decimals: 18 },
5050
+ rpcUrls: ["https://polygon.llamarpc.com"],
5051
+ blockExplorerUrls: ["https://polygonscan.com"]
5052
+ },
5053
+ 8453: {
5054
+ chainId: "0x2105",
5055
+ chainName: "Base",
5056
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5057
+ rpcUrls: ["https://mainnet.base.org"],
5058
+ blockExplorerUrls: ["https://basescan.org"]
5059
+ },
5060
+ 56: {
5061
+ chainId: "0x38",
5062
+ chainName: "BNB Smart Chain",
5063
+ nativeCurrency: { name: "BNB", symbol: "BNB", decimals: 18 },
5064
+ rpcUrls: ["https://bsc-dataseed.binance.org"],
5065
+ blockExplorerUrls: ["https://bscscan.com"]
5066
+ },
5067
+ 169: {
5068
+ chainId: "0xa9",
5069
+ chainName: "Manta Pacific",
5070
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5071
+ rpcUrls: ["https://pacific-rpc.manta.network/http"],
5072
+ blockExplorerUrls: ["https://pacific-explorer.manta.network"]
5073
+ },
5074
+ 204: {
5075
+ chainId: "0xcc",
5076
+ chainName: "opBNB",
5077
+ nativeCurrency: { name: "BNB", symbol: "BNB", decimals: 18 },
5078
+ rpcUrls: ["https://opbnb-mainnet-rpc.bnbchain.org"],
5079
+ blockExplorerUrls: ["https://opbnbscan.com"]
5080
+ },
5081
+ 1030: {
5082
+ chainId: "0x406",
5083
+ chainName: "Conflux eSpace",
5084
+ nativeCurrency: { name: "CFX", symbol: "CFX", decimals: 18 },
5085
+ rpcUrls: ["https://evm.confluxrpc.com"],
5086
+ blockExplorerUrls: ["https://evm.confluxscan.net"]
5087
+ },
5088
+ 5e3: {
5089
+ chainId: "0x1388",
5090
+ chainName: "Mantle",
5091
+ nativeCurrency: { name: "MNT", symbol: "MNT", decimals: 18 },
5092
+ rpcUrls: ["https://rpc.mantle.xyz"],
5093
+ blockExplorerUrls: ["https://explorer.mantle.xyz"]
5094
+ },
5095
+ 42220: {
5096
+ chainId: "0xa4ec",
5097
+ chainName: "Celo",
5098
+ nativeCurrency: { name: "CELO", symbol: "CELO", decimals: 18 },
5099
+ rpcUrls: ["https://forno.celo.org"],
5100
+ blockExplorerUrls: ["https://explorer.celo.org"]
5101
+ },
5102
+ 59144: {
5103
+ chainId: "0xe708",
5104
+ chainName: "Linea",
5105
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5106
+ rpcUrls: ["https://rpc.linea.build"],
5107
+ blockExplorerUrls: ["https://lineascan.build"]
5108
+ },
5109
+ 81457: {
5110
+ chainId: "0x13e31",
5111
+ chainName: "Blast",
5112
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5113
+ rpcUrls: ["https://rpc.blast.io"],
5114
+ blockExplorerUrls: ["https://blastscan.io"]
5115
+ },
5116
+ 534352: {
5117
+ chainId: "0x82750",
5118
+ chainName: "Scroll",
5119
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5120
+ rpcUrls: ["https://rpc.scroll.io"],
5121
+ blockExplorerUrls: ["https://scrollscan.com"]
5122
+ },
5123
+ 25: {
5124
+ chainId: "0x19",
5125
+ chainName: "Cronos",
5126
+ nativeCurrency: { name: "CRO", symbol: "CRO", decimals: 18 },
5127
+ rpcUrls: ["https://evm.cronos.org"],
5128
+ blockExplorerUrls: ["https://cronoscan.com"]
5129
+ },
5130
+ 100: {
5131
+ chainId: "0x64",
5132
+ chainName: "Gnosis",
5133
+ nativeCurrency: { name: "xDAI", symbol: "xDAI", decimals: 18 },
5134
+ rpcUrls: ["https://rpc.gnosischain.com"],
5135
+ blockExplorerUrls: ["https://gnosisscan.io"]
5136
+ },
5137
+ 146: {
5138
+ chainId: "0x92",
5139
+ chainName: "Sonic",
5140
+ nativeCurrency: { name: "S", symbol: "S", decimals: 18 },
5141
+ rpcUrls: ["https://rpc.soniclabs.com"],
5142
+ blockExplorerUrls: ["https://sonicscan.org"]
5143
+ },
5144
+ 250: {
5145
+ chainId: "0xfa",
5146
+ chainName: "Fantom Opera",
5147
+ nativeCurrency: { name: "FTM", symbol: "FTM", decimals: 18 },
5148
+ rpcUrls: ["https://rpcapi.fantom.network"],
5149
+ blockExplorerUrls: ["https://ftmscan.com"]
5150
+ },
5151
+ 324: {
5152
+ chainId: "0x144",
5153
+ chainName: "zkSync Era",
5154
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5155
+ rpcUrls: ["https://mainnet.era.zksync.io"],
5156
+ blockExplorerUrls: ["https://explorer.zksync.io"]
5157
+ },
5158
+ 1088: {
5159
+ chainId: "0x440",
5160
+ chainName: "Metis Andromeda",
5161
+ nativeCurrency: { name: "Metis", symbol: "METIS", decimals: 18 },
5162
+ rpcUrls: ["https://andromeda.metis.io/?owner=1088"],
5163
+ blockExplorerUrls: ["https://andromeda-explorer.metis.io"]
5164
+ },
5165
+ 1101: {
5166
+ chainId: "0x44d",
5167
+ chainName: "Polygon zkEVM",
5168
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5169
+ rpcUrls: ["https://zkevm-rpc.com"],
5170
+ blockExplorerUrls: ["https://zkevm.polygonscan.com"]
5171
+ },
5172
+ 1284: {
5173
+ chainId: "0x504",
5174
+ chainName: "Moonbeam",
5175
+ nativeCurrency: { name: "GLMR", symbol: "GLMR", decimals: 18 },
5176
+ rpcUrls: ["https://rpc.api.moonbeam.network"],
5177
+ blockExplorerUrls: ["https://moonscan.io"]
5178
+ },
5179
+ 1285: {
5180
+ chainId: "0x505",
5181
+ chainName: "Moonriver",
5182
+ nativeCurrency: { name: "MOVR", symbol: "MOVR", decimals: 18 },
5183
+ rpcUrls: ["https://rpc.api.moonriver.moonbeam.network"],
5184
+ blockExplorerUrls: ["https://moonriver.moonscan.io"]
5185
+ },
5186
+ 2222: {
5187
+ chainId: "0x8ae",
5188
+ chainName: "Kava EVM",
5189
+ nativeCurrency: { name: "KAVA", symbol: "KAVA", decimals: 18 },
5190
+ rpcUrls: ["https://evm.kava.io"],
5191
+ blockExplorerUrls: ["https://explorer.kava.io"]
5192
+ },
5193
+ 8217: {
5194
+ chainId: "0x2019",
5195
+ chainName: "Klaytn",
5196
+ nativeCurrency: { name: "KLAY", symbol: "KLAY", decimals: 18 },
5197
+ rpcUrls: ["https://public-en-cypress.klaytn.net"],
5198
+ blockExplorerUrls: ["https://scope.klaytn.com"]
5199
+ },
5200
+ 43114: {
5201
+ chainId: "0xa86a",
5202
+ chainName: "Avalanche C-Chain",
5203
+ nativeCurrency: { name: "AVAX", symbol: "AVAX", decimals: 18 },
5204
+ rpcUrls: ["https://api.avax.network/ext/bc/C/rpc"],
5205
+ blockExplorerUrls: ["https://snowtrace.io"]
5206
+ },
5207
+ 1313161554: {
5208
+ chainId: "0x4e454152",
5209
+ chainName: "Aurora",
5210
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
5211
+ rpcUrls: ["https://mainnet.aurora.dev"],
5212
+ blockExplorerUrls: ["https://aurorascan.dev"]
5213
+ }
5214
+ };
5022
5215
  function isNativeAddress(addr) {
5023
5216
  if (!addr) return false;
5024
5217
  const a2 = addr.toLowerCase();
@@ -5545,12 +5738,67 @@ class EvmChainStrategy {
5545
5738
  }
5546
5739
  return Number(formatUnits(totalFeeWei, 18));
5547
5740
  }
5741
+ /**
5742
+ * Switch wallet to the specified chain
5743
+ * If the chain is not in the wallet, attempts to add it
5744
+ */
5745
+ async switchToChain(chainId) {
5746
+ if (!this.walletClient) {
5747
+ throw new WalletNotConnectedError("evm");
5748
+ }
5749
+ const chainIdHex = `0x${chainId.toString(16)}`;
5750
+ try {
5751
+ await this.walletClient.request({
5752
+ method: "wallet_switchEthereumChain",
5753
+ params: [{ chainId: chainIdHex }]
5754
+ });
5755
+ console.log(`Switched to chain ${chainId}`);
5756
+ } catch (switchError) {
5757
+ const error = switchError;
5758
+ if (error.code === 4902) {
5759
+ const networkConfig = NETWORK_CONFIGS[chainId];
5760
+ if (!networkConfig) {
5761
+ throw new InvalidStepsError(
5762
+ "evm",
5763
+ `No network configuration found for chain ID ${chainId}`
5764
+ );
5765
+ }
5766
+ try {
5767
+ await this.walletClient.request({
5768
+ method: "wallet_addEthereumChain",
5769
+ params: [networkConfig]
5770
+ });
5771
+ console.log(`Added and switched to chain ${chainId}`);
5772
+ } catch (addError) {
5773
+ throw new TransactionFailedError(
5774
+ "evm",
5775
+ `Failed to add network ${networkConfig.chainName}`,
5776
+ void 0,
5777
+ addError instanceof Error ? addError : void 0
5778
+ );
5779
+ }
5780
+ } else {
5781
+ throw toChainStrategyError(switchError, "evm", "network-switch");
5782
+ }
5783
+ }
5784
+ }
5548
5785
  async executeSteps(steps, _context, onStepComplete) {
5549
5786
  if (!this.isConnected() || !this.walletClient) {
5550
5787
  throw new WalletNotConnectedError("evm");
5551
5788
  }
5552
5789
  this.validateSteps(steps);
5553
5790
  try {
5791
+ const firstChainKey = steps[0]?.chainKey;
5792
+ if (firstChainKey && this.config.chainKeyToId) {
5793
+ const requiredChainId = this.config.chainKeyToId[firstChainKey.toLowerCase()];
5794
+ const currentChainId = this.walletClient.chain?.id;
5795
+ if (requiredChainId && currentChainId !== requiredChainId) {
5796
+ console.log(`Switching from chain ${currentChainId} to ${requiredChainId}`);
5797
+ await this.switchToChain(requiredChainId);
5798
+ } else {
5799
+ console.log(`Already on correct chain ${currentChainId}`);
5800
+ }
5801
+ }
5554
5802
  let firstTxHash;
5555
5803
  const totalSteps = steps.length;
5556
5804
  for (let i3 = 0; i3 < steps.length; i3++) {
@@ -7510,7 +7758,8 @@ const useAutoSelectNetwork = ({
7510
7758
  evmIsConnected
7511
7759
  }) => {
7512
7760
  const { hasAnyWallet } = useConnectedWalletsStore();
7513
- const { chains, setFromChain } = useChainsStore();
7761
+ const { chains, setFromChain, setToChain } = useChainsStore();
7762
+ const { lastConnectionAddressType } = useWalletSelectModal();
7514
7763
  const previousHadWallet = useRef(hasAnyWallet());
7515
7764
  useEffect(() => {
7516
7765
  const currentHasWallet = hasAnyWallet();
@@ -7529,7 +7778,11 @@ const useAutoSelectNetwork = ({
7529
7778
  (chain2) => chain2.chainKey.toLowerCase() === targetChainKey
7530
7779
  );
7531
7780
  if (matchingChain) {
7532
- setFromChain(matchingChain);
7781
+ if (lastConnectionAddressType === "dst") {
7782
+ setToChain(matchingChain);
7783
+ } else {
7784
+ setFromChain(matchingChain);
7785
+ }
7533
7786
  }
7534
7787
  }
7535
7788
  }
@@ -7540,7 +7793,9 @@ const useAutoSelectNetwork = ({
7540
7793
  evmIsConnected,
7541
7794
  hasAnyWallet,
7542
7795
  chains,
7543
- setFromChain
7796
+ setFromChain,
7797
+ setToChain,
7798
+ lastConnectionAddressType
7544
7799
  ]);
7545
7800
  };
7546
7801
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
@@ -26153,7 +26408,7 @@ class WalletConnectModal {
26153
26408
  }
26154
26409
  async initUi() {
26155
26410
  if (typeof window !== "undefined") {
26156
- await import("./index-ClSyIB0n.js");
26411
+ await import("./index-CA5BH32n.js");
26157
26412
  const modal = document.createElement("wcm-modal");
26158
26413
  document.body.insertAdjacentElement("beforeend", modal);
26159
26414
  OptionsCtrl.setIsUiLoaded(true);
@@ -27057,4 +27312,4 @@ export {
27057
27312
  calculateMinReceived as y,
27058
27313
  getQuoteDetails as z
27059
27314
  };
27060
- //# sourceMappingURL=index-D7lsGQY9.js.map
27315
+ //# sourceMappingURL=index-BgRN7kwd.js.map