coinley-pay 0.20.0 → 0.21.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.
@@ -5,7 +5,7 @@ import { jsxs, jsx, Fragment } from "react/jsx-runtime";
5
5
  import { useState, useRef, useEffect, useCallback, useMemo } from "react";
6
6
  import { useConnect, useAccount, useSwitchChain, useSendTransaction, useWaitForTransactionReceipt, WagmiProvider, useDisconnect } from "wagmi";
7
7
  import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
8
- import { s as sdkAnalytics, c as clarityAnalytics, d as dist, a as Buffer2, B as Buffer$1, g as getCurrencyInfo, p as prefetchRates, i as isSupportedCurrency, b as convertToUSD, f as formatCurrency } from "./index-YblNXa3i.js";
8
+ import { s as sdkAnalytics, c as clarityAnalytics, d as dist, a as Buffer2, B as Buffer$1, g as getCurrencyInfo, p as prefetchRates, i as isSupportedCurrency, b as convertToUSD, f as formatCurrency } from "./index-BLIQ06qE.js";
9
9
  import { createConfig, fallback, http, getAccount as getAccount$1, getWalletClient, simulateContract, writeContract, readContract, waitForTransactionReceipt, estimateFeesPerGas as estimateFeesPerGas$1 } from "@wagmi/core";
10
10
  import { injected, metaMask, coinbaseWallet, walletConnect } from "@wagmi/connectors";
11
11
  import { defineChain as defineChain$1, erc20Abi, http as http$1, createPublicClient, fallback as fallback$1 } from "viem";
@@ -2414,28 +2414,36 @@ class SimplePaymentAPI {
2414
2414
  async getDepositBalance(paymentId) {
2415
2415
  return await this.request(`/api/deposits/balance/${paymentId}`);
2416
2416
  }
2417
- // ==================== BRIDGE PROVIDER PROXY API ====================
2418
- async getAcrossTokens() {
2419
- const response = await this.request("/api/bridge/across/tokens", {
2420
- timeout: 3e4
2421
- });
2422
- return response.tokens || [];
2423
- }
2424
- async getAcrossApproval(params) {
2425
- const response = await this.request("/api/bridge/across/approval", {
2417
+ // ==================== BRIDGE ROUTING API ====================
2418
+ async getBridgeRoute(params) {
2419
+ const response = await this.request("/api/bridge/quote", {
2426
2420
  method: "POST",
2427
2421
  body: JSON.stringify(params),
2428
2422
  timeout: 45e3
2429
2423
  });
2430
- return response.quote;
2424
+ return response.route;
2431
2425
  }
2432
- async getAcrossStatus(params) {
2426
+ async getBridgeTokens(chainId) {
2427
+ const query = new URLSearchParams({ chainId: String(chainId) }).toString();
2428
+ const response = await this.request(`/api/bridge/tokens?${query}`, {
2429
+ timeout: 3e4
2430
+ });
2431
+ return response.tokens || [];
2432
+ }
2433
+ async getBridgeStatusV2(params) {
2433
2434
  const query = new URLSearchParams(params).toString();
2434
- const response = await this.request(`/api/bridge/across/status?${query}`, {
2435
+ const response = await this.request(`/api/bridge/status?${query}`, {
2435
2436
  timeout: 2e4
2436
2437
  });
2437
2438
  return response.status;
2438
2439
  }
2440
+ async trackBridge(params) {
2441
+ return await this.request("/api/bridge/track", {
2442
+ method: "POST",
2443
+ body: JSON.stringify(params),
2444
+ timeout: 2e4
2445
+ });
2446
+ }
2439
2447
  /**
2440
2448
  * Check if a network supports deposit address payments
2441
2449
  * @param {number|string} chainId - Chain ID
@@ -2447,8 +2455,6 @@ class SimplePaymentAPI {
2447
2455
  }
2448
2456
  }
2449
2457
  const LIFI_API_URL = "https://li.quest/v1";
2450
- const LIFI_API_KEY = "c344f311-d6d3-4f0c-8ea4-f3aee507f37e.78f5b82d-440a-4463-a841-c6bf11078d22";
2451
- const LIFI_INTEGRATOR = "coinley";
2452
2458
  const LIFI_SOLANA_CHAIN_ID = 1151111081099710;
2453
2459
  const BRIDGE_DESTINATION_PRIORITY = [
2454
2460
  "base",
@@ -2535,26 +2541,6 @@ const SOLANA_TOKEN_ADDRESSES = {
2535
2541
  USDC: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
2536
2542
  USDT: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"
2537
2543
  };
2538
- const extractBridgeTokens = (chainData) => {
2539
- const chainId = parseInt((chainData == null ? void 0 : chainData.id) || (chainData == null ? void 0 : chainData.chainId), 10);
2540
- const lifiTokens = (chainData == null ? void 0 : chainData.tokens) || (chainData == null ? void 0 : chainData.featuredTokens) || [];
2541
- let usdc = null;
2542
- let usdt = null;
2543
- for (const token of lifiTokens) {
2544
- const symbol = (token.symbol || "").toUpperCase();
2545
- if (!usdc && symbol.startsWith("USDC") && token.address) {
2546
- usdc = { address: token.address, decimals: token.decimals || 6 };
2547
- }
2548
- if (!usdt && symbol.startsWith("USDT") && token.address) {
2549
- usdt = { address: token.address, decimals: token.decimals || 6 };
2550
- }
2551
- }
2552
- const known = Number.isFinite(chainId) ? getKnownBridgeTokens(chainId) : {};
2553
- return {
2554
- usdc: usdc || known.usdc || null,
2555
- usdt: usdt || known.usdt || null
2556
- };
2557
- };
2558
2544
  const getBridgeTokenAddress = (symbol, bridgeTokens) => {
2559
2545
  var _a, _b;
2560
2546
  const upper = symbol == null ? void 0 : symbol.toUpperCase();
@@ -2658,44 +2644,29 @@ const usePaymentFlow = (apiUrl, apiKey, apiSecret) => {
2658
2644
  merchantNetworks.filter((n) => n.chainId && n.shortName !== "solana" && n.chainType !== "solana").map((n) => parseInt(n.chainId))
2659
2645
  );
2660
2646
  if (merchantChainIds.size === 0) return;
2661
- const response = await fetch(`${LIFI_API_URL}/chains?chainTypes=EVM`, {
2662
- method: "GET",
2663
- headers: {
2664
- "Content-Type": "application/json",
2665
- ...LIFI_API_KEY ? { "x-lifi-api-key": LIFI_API_KEY } : {}
2666
- },
2667
- signal: AbortSignal.timeout(1e4)
2668
- });
2669
- if (!response.ok) return;
2670
- const data = await response.json();
2671
- const lifiChains = data.chains || data || [];
2672
2647
  const bestDest = getBestDestinationChain(merchantNetworks);
2673
2648
  if (!bestDest) return;
2674
2649
  const destChainId = parseInt(bestDest.chainId);
2675
- const destLifiChain = lifiChains.find((c) => parseInt(c.id || c.chainId, 10) === destChainId);
2676
- const destBridgeTokens = destLifiChain ? extractBridgeTokens(destLifiChain) : getKnownBridgeTokens(destChainId);
2677
- const bridgeNets = lifiChains.filter((chain) => {
2678
- const chainId = parseInt(chain.id || chain.chainId, 10);
2650
+ const destBridgeTokens = getKnownBridgeTokens(destChainId);
2651
+ const bridgeNets = Object.entries(CHAIN_ID_TO_SHORT_NAME).filter(([chainIdText]) => {
2652
+ const chainId = parseInt(chainIdText, 10);
2679
2653
  if (!chainId) return false;
2680
2654
  if (merchantChainIds.has(chainId)) return false;
2681
- const bridgeTokens = extractBridgeTokens(chain);
2682
- if (!bridgeTokens.usdc && !bridgeTokens.usdt) return false;
2683
- return true;
2684
- }).map((chain) => {
2685
- const chainId = parseInt(chain.id || chain.chainId, 10);
2686
- const shortName = CHAIN_ID_TO_SHORT_NAME[chainId] || chain.name;
2687
- const bridgeTokens = extractBridgeTokens(chain);
2655
+ const bridgeTokens = getKnownBridgeTokens(chainId);
2656
+ return !!(bridgeTokens.usdc || bridgeTokens.usdt);
2657
+ }).map(([chainIdText, shortName]) => {
2658
+ const chainId = parseInt(chainIdText, 10);
2659
+ const bridgeTokens = getKnownBridgeTokens(chainId);
2688
2660
  return {
2689
2661
  id: `bridge-${chainId}`,
2690
- name: chain.name || chain.displayName || `Chain ${chainId}`,
2662
+ name: shortName || `Chain ${chainId}`,
2691
2663
  shortName: shortName || `chain-${chainId}`,
2692
2664
  chainId,
2693
2665
  chainType: "evm",
2694
2666
  isBridgeNetwork: true,
2695
2667
  bridgeDestination: { ...bestDest, bridgeTokens: destBridgeTokens },
2696
2668
  bridgeTokens,
2697
- lifiChainData: chain,
2698
- logo: chain.logoURI || null
2669
+ logo: null
2699
2670
  };
2700
2671
  });
2701
2672
  setBridgeNetworks(bridgeNets);
@@ -4021,7 +3992,8 @@ const useTransactionHandling = (paymentData, selectedToken, selectedNetwork, add
4021
3992
  setTransactionStep("swapping");
4022
3993
  const action = swapQuote.isSwap && !swapQuote.isSameChain ? "swap & bridge" : "swap";
4023
3994
  onProgress == null ? void 0 : onProgress("swapping", `Swapping ${swapQuote.originTokenSymbol} → ${swapQuote.destTokenSymbol}...`);
4024
- const result = await bridgeHook.executeBridge(swapQuote, walletClient, (step, msg) => {
3995
+ const quoteWithPaymentId = paymentId ? { ...swapQuote, paymentId } : swapQuote;
3996
+ const result = await bridgeHook.executeBridge(quoteWithPaymentId, walletClient, (step, msg) => {
4025
3997
  onProgress == null ? void 0 : onProgress(step, msg);
4026
3998
  });
4027
3999
  if (!result.success) {
@@ -21123,7 +21095,7 @@ const WalletSelector = ({
21123
21095
  try {
21124
21096
  setAppKitError(null);
21125
21097
  setWalletConnectAddress(solanaAccountState.address);
21126
- const { createWalletConnectAdapter } = await import("./appKitSolana-QAp0wzR5.js");
21098
+ const { createWalletConnectAdapter } = await import("./appKitSolana-KE60037B.js");
21127
21099
  const adapter = createWalletConnectAdapter(solanaAccountState.address);
21128
21100
  await solanaWallet.connectWalletConnect(adapter, solanaAccountState.address);
21129
21101
  console.log("✅ WalletConnect synced with SDK");
@@ -21228,7 +21200,7 @@ const WalletSelector = ({
21228
21200
  setAppKitLoading(true);
21229
21201
  setAppKitError(null);
21230
21202
  try {
21231
- const { initializeAppKitEVM, openAppKitModal } = await import("./appKitEVM-jh6msvrg.js");
21203
+ const { initializeAppKitEVM, openAppKitModal } = await import("./appKitEVM-Bs-au6VA.js");
21232
21204
  await initializeAppKitEVM(wagmiConfig);
21233
21205
  await openAppKitModal();
21234
21206
  } catch (error) {
@@ -21248,7 +21220,7 @@ const WalletSelector = ({
21248
21220
  setAppKitError(null);
21249
21221
  try {
21250
21222
  console.log("📦 Loading AppKit Solana module...");
21251
- const { initializeAppKitSolana } = await import("./appKitSolana-QAp0wzR5.js");
21223
+ const { initializeAppKitSolana } = await import("./appKitSolana-KE60037B.js");
21252
21224
  console.log("✅ Module loaded, initializing...");
21253
21225
  const modal = await initializeAppKitSolana(solanaWallet);
21254
21226
  console.log("✅ AppKit Solana initialized successfully");
@@ -21494,94 +21466,6 @@ const PaymentAlternatives = ({ currentPaymentType, onSelectMethod, isDepositSupp
21494
21466
  }) })
21495
21467
  ] });
21496
21468
  };
21497
- const __vite_import_meta_env__ = {};
21498
- const ACROSS_FALLBACK_ENABLED = (__vite_import_meta_env__ == null ? void 0 : __vite_import_meta_env__.VITE_COINLEY_ENABLE_ACROSS_FALLBACK) !== "false";
21499
- const ACROSS_SUPPORTED_USDC_SOURCE_CHAINS = /* @__PURE__ */ new Set([
21500
- 1,
21501
- 10,
21502
- 130,
21503
- 137,
21504
- 143,
21505
- 232,
21506
- 480,
21507
- 999,
21508
- 1868,
21509
- 42161,
21510
- 534352,
21511
- 57073,
21512
- 59144,
21513
- 324
21514
- ]);
21515
- const ACROSS_SUPPORTED_USDT_SOURCE_CHAINS = /* @__PURE__ */ new Set([
21516
- 1,
21517
- 10,
21518
- 130,
21519
- 137,
21520
- 143,
21521
- 999,
21522
- 1868,
21523
- 42161,
21524
- 534352,
21525
- 59144,
21526
- 57073,
21527
- 324
21528
- ]);
21529
- const ACROSS_SUPPORTED_DESTINATION_CHAINS = /* @__PURE__ */ new Set([
21530
- 8453,
21531
- // Base
21532
- 42161,
21533
- // Arbitrum
21534
- 10,
21535
- // Optimism
21536
- 137,
21537
- // Polygon
21538
- 56
21539
- // BSC
21540
- ]);
21541
- const TOKEN_ALIASES = {
21542
- USDC: /* @__PURE__ */ new Set(["USDC", "USDC.E", "USDBC", "USDC0", "AXLUSDC"]),
21543
- USDT: /* @__PURE__ */ new Set(["USDT", "USDT0", "USDT.E", "USDTB", "AXLUSDT"])
21544
- };
21545
- const normalizeAcrossSymbol = (symbol) => {
21546
- const upper = String(symbol || "").toUpperCase();
21547
- if (TOKEN_ALIASES.USDC.has(upper)) return "USDC";
21548
- if (TOKEN_ALIASES.USDT.has(upper)) return "USDT";
21549
- if (upper === "ETH" || upper === "WETH") return upper;
21550
- return upper;
21551
- };
21552
- const isAcrossRouteCandidate = ({ originChainId, destChainId, originTokenSymbol, destTokenSymbol }) => {
21553
- if (!ACROSS_FALLBACK_ENABLED) return false;
21554
- if (!ACROSS_SUPPORTED_DESTINATION_CHAINS.has(Number(destChainId))) return false;
21555
- const originSymbol = normalizeAcrossSymbol(originTokenSymbol);
21556
- const destSymbol = normalizeAcrossSymbol(destTokenSymbol);
21557
- if (originSymbol !== destSymbol) return false;
21558
- if (originSymbol === "USDC") {
21559
- return ACROSS_SUPPORTED_USDC_SOURCE_CHAINS.has(Number(originChainId));
21560
- }
21561
- if (originSymbol === "USDT") {
21562
- return ACROSS_SUPPORTED_USDT_SOURCE_CHAINS.has(Number(originChainId));
21563
- }
21564
- return false;
21565
- };
21566
- const pickAcrossToken = (tokens, chainId, symbol, address) => {
21567
- const normalizedSymbol = normalizeAcrossSymbol(symbol);
21568
- const normalizedAddress = typeof address === "string" ? address.toLowerCase() : null;
21569
- const chainTokens = (tokens || []).filter((token) => Number(token.chainId) === Number(chainId));
21570
- if (normalizedAddress && normalizedAddress !== "native") {
21571
- const byAddress = chainTokens.find((token) => {
21572
- var _a;
21573
- return ((_a = token.address) == null ? void 0 : _a.toLowerCase()) === normalizedAddress;
21574
- });
21575
- if (byAddress) return byAddress;
21576
- }
21577
- const aliases = TOKEN_ALIASES[normalizedSymbol] || /* @__PURE__ */ new Set([normalizedSymbol]);
21578
- const candidates = chainTokens.filter((token) => aliases.has(String(token.symbol || "").toUpperCase()));
21579
- if (candidates.length === 0) return null;
21580
- return candidates.find((token) => {
21581
- const price = Number(token.priceUsd || 0);
21582
- return price >= 0.95 && price <= 1.05;
21583
- }) || candidates[0];
21584
- };
21585
21469
  const createDebugId = (prefix = "lifi-sdk") => `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
21586
21470
  const normalizeAddress = (value) => {
21587
21471
  if (typeof value !== "string") return null;
@@ -21592,152 +21476,46 @@ const extractQuoteRecipient = (quote) => {
21592
21476
  var _a, _b, _c;
21593
21477
  return normalizeAddress((_a = quote == null ? void 0 : quote.action) == null ? void 0 : _a.toAddress) || normalizeAddress(quote == null ? void 0 : quote.toAddress) || normalizeAddress((_b = quote == null ? void 0 : quote.estimate) == null ? void 0 : _b.toAddress) || normalizeAddress((_c = quote == null ? void 0 : quote.transactionRequest) == null ? void 0 : _c.toAddress) || null;
21594
21478
  };
21595
- let acrossTokenCache = null;
21596
- let acrossTokenCacheTime = 0;
21597
- const ACROSS_TOKEN_CACHE_TTL_MS = 10 * 60 * 1e3;
21598
- const fetchAcrossTokens = async (acrossApi) => {
21599
- if (acrossTokenCache && Date.now() - acrossTokenCacheTime < ACROSS_TOKEN_CACHE_TTL_MS) {
21600
- return acrossTokenCache;
21601
- }
21602
- if (!(acrossApi == null ? void 0 : acrossApi.getAcrossTokens)) {
21603
- throw new Error("Across server proxy is not configured");
21604
- }
21605
- const tokens = await acrossApi.getAcrossTokens();
21606
- acrossTokenCache = Array.isArray(tokens) ? tokens : [];
21607
- acrossTokenCacheTime = Date.now();
21608
- return acrossTokenCache;
21479
+ const formatTokenAmount = (amount, decimals = 6, symbol = "") => {
21480
+ if (!amount) return symbol ? `0 ${symbol}` : "0";
21481
+ try {
21482
+ const raw = BigInt(amount);
21483
+ const divisor = 10n ** BigInt(decimals || 0);
21484
+ const whole = raw / divisor;
21485
+ const fraction = raw % divisor;
21486
+ const fractionText = fraction.toString().padStart(decimals || 0, "0").slice(0, 4).replace(/0+$/, "");
21487
+ return `${whole.toString()}${fractionText ? `.${fractionText}` : ""}${symbol ? ` ${symbol}` : ""}`;
21488
+ } catch {
21489
+ return symbol ? `${amount} ${symbol}` : String(amount);
21490
+ }
21609
21491
  };
21610
- const getAcrossQuote = async ({
21611
- originChainId,
21612
- destChainId,
21613
- originTokenAddress,
21614
- originTokenSymbol,
21615
- destTokenAddress,
21616
- destTokenSymbol,
21617
- amount,
21618
- recipient,
21619
- fromAddress,
21620
- debugId,
21621
- attemptId,
21622
- attemptMeta,
21623
- acrossApi
21624
- }) => {
21625
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
21626
- if (!isAcrossRouteCandidate({ originChainId, destChainId, originTokenSymbol, destTokenSymbol })) {
21627
- throw new Error("Across route not eligible for this chain/token pair");
21628
- }
21629
- const tokens = await fetchAcrossTokens(acrossApi);
21630
- const inputToken = pickAcrossToken(tokens, originChainId, originTokenSymbol, originTokenAddress);
21631
- const outputToken = pickAcrossToken(tokens, destChainId, destTokenSymbol, destTokenAddress);
21632
- if (!inputToken || !outputToken) {
21633
- throw new Error("Across token not available for this route");
21634
- }
21635
- const toAmountRaw = BigInt(Math.ceil(parseFloat(amount) * Math.pow(10, outputToken.decimals || 6))).toString();
21636
- const params = {
21637
- tradeType: "exactOutput",
21638
- amount: toAmountRaw,
21639
- originChainId: String(originChainId),
21640
- destinationChainId: String(destChainId),
21641
- inputToken: inputToken.address,
21642
- outputToken: outputToken.address,
21643
- depositor: fromAddress,
21644
- recipient,
21645
- slippage: "0.005"
21646
- };
21647
- console.log("[Across] Requesting fallback quote:", {
21648
- debugId,
21649
- fromChain: originChainId,
21650
- toChain: destChainId,
21651
- fromToken: `${inputToken.symbol} (${inputToken.address.slice(0, 10)}...)`,
21652
- toToken: `${outputToken.symbol} (${outputToken.address.slice(0, 10)}...)`,
21653
- recipient,
21654
- fromAddress,
21655
- requestedOutputAmount: toAmountRaw
21656
- });
21657
- const quote = await acrossApi.getAcrossApproval(params);
21658
- const bridgeStep = ((_a = quote.steps) == null ? void 0 : _a.bridge) || {};
21659
- const feeAmountRaw = ((_b = bridgeStep.fees) == null ? void 0 : _b.amount) || ((_c = quote.fees) == null ? void 0 : _c.total) || "0";
21660
- const feeDecimals = ((_e = (_d = bridgeStep.fees) == null ? void 0 : _d.token) == null ? void 0 : _e.decimals) || inputToken.decimals || 6;
21661
- const feeUsd = Number(feeAmountRaw) / Math.pow(10, feeDecimals);
21662
- const inputAmountRaw = bridgeStep.inputAmount || ((_g = (_f = quote.checks) == null ? void 0 : _f.balance) == null ? void 0 : _g.expected) || ((_i = (_h = quote.checks) == null ? void 0 : _h.allowance) == null ? void 0 : _i.expected);
21663
- const outputAmountRaw = bridgeStep.outputAmount || toAmountRaw;
21664
- const inputAmount = inputAmountRaw ? `${(Number(inputAmountRaw) / Math.pow(10, inputToken.decimals || 6)).toFixed(4)} ${inputToken.symbol}` : amount;
21665
- const outputAmount = outputAmountRaw ? (Number(outputAmountRaw) / Math.pow(10, outputToken.decimals || 6)).toFixed(4) : amount;
21666
- const parsedQuote = {
21667
- debugId,
21668
- provider: "across",
21669
- raw: quote,
21670
- originChainId,
21671
- destChainId,
21672
- originChainName: CHAIN_ID_TO_SHORT_NAME[originChainId] || `Chain ${originChainId}`,
21673
- destChainName: CHAIN_ID_TO_SHORT_NAME[destChainId] || `Chain ${destChainId}`,
21674
- originTokenSymbol: inputToken.symbol || originTokenSymbol,
21675
- originTokenAddress: inputToken.address,
21676
- inputAmount,
21677
- destTokenSymbol: outputToken.symbol || destTokenSymbol,
21678
- destTokenAddress: outputToken.address,
21679
- outputAmount,
21680
- bridgeFee: Number.isFinite(feeUsd) ? feeUsd.toFixed(4) : "0",
21681
- bridgeFeeCurrency: "USD",
21682
- estimatedTime: quote.expectedFillTime || quote.expectedFillTimeSec || 5,
21683
- steps: [bridgeStep].filter(Boolean),
21684
- tool: "across",
21685
- toolDetails: { name: "Across" },
21686
- isSwap: inputToken.symbol !== outputToken.symbol,
21687
- isSameChain: Number(originChainId) === Number(destChainId),
21688
- tradeType: "EXACT_OUTPUT",
21689
- requestedRecipient: normalizeAddress(recipient),
21690
- effectiveRecipient: normalizeAddress(recipient),
21691
- transactionRequest: quote.swapTx,
21692
- approvalTxns: quote.approvalTxns || [],
21693
- approvalAddress: ((_k = (_j = quote.checks) == null ? void 0 : _j.allowance) == null ? void 0 : _k.spender) || ((_m = (_l = quote.approvalTxns) == null ? void 0 : _l[0]) == null ? void 0 : _m.to) || null,
21694
- attemptId,
21695
- selectionSnapshot: (attemptMeta == null ? void 0 : attemptMeta.selectionSnapshot) ?? null
21696
- };
21697
- console.log("[Across] Quote response:", {
21698
- debugId,
21699
- attemptId,
21700
- inputToken: parsedQuote.originTokenSymbol,
21701
- outputToken: parsedQuote.destTokenSymbol,
21702
- inputAmount: parsedQuote.inputAmount,
21703
- outputAmount: parsedQuote.outputAmount,
21704
- estimatedTime: parsedQuote.estimatedTime,
21705
- hasApproval: parsedQuote.approvalTxns.length > 0,
21706
- hasSwapTx: !!parsedQuote.transactionRequest
21707
- });
21708
- return parsedQuote;
21492
+ const buildApprovalData = (spender, amount) => {
21493
+ const cleanSpender = normalizeAddress(spender);
21494
+ if (!cleanSpender) throw new Error("Invalid bridge approval spender");
21495
+ const rawAmount = BigInt(amount || 0).toString(16);
21496
+ return "0x095ea7b3" + cleanSpender.slice(2).padStart(64, "0") + rawAmount.padStart(64, "0");
21709
21497
  };
21710
21498
  const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21711
21499
  const [bridgeStatus, setBridgeStatus] = useState("idle");
21712
21500
  const [bridgeQuote, setBridgeQuote] = useState(null);
21713
21501
  const [bridgeError, setBridgeError] = useState(null);
21714
21502
  const [bridgeChains, setBridgeChains] = useState([]);
21715
- const acrossApiRef = useRef(null);
21716
- acrossApiRef.current = apiUrl && publicKeyOrApiKey ? new SimplePaymentAPI(apiUrl, publicKeyOrApiKey, apiSecret) : null;
21717
- const headers = {
21718
- "Content-Type": "application/json",
21719
- ...{ "x-lifi-api-key": LIFI_API_KEY }
21720
- };
21503
+ const bridgeApiRef = useRef(null);
21504
+ bridgeApiRef.current = apiUrl && publicKeyOrApiKey ? new SimplePaymentAPI(apiUrl, publicKeyOrApiKey, apiSecret) : null;
21721
21505
  const fetchBridgeChains = useCallback(async () => {
21722
- try {
21723
- const res = await fetch(`${LIFI_API_URL}/chains?chainTypes=EVM,SVM`, {
21724
- headers,
21725
- signal: AbortSignal.timeout(1e4)
21726
- });
21727
- if (!res.ok) return [];
21728
- const data = await res.json();
21729
- const chains = data.chains || data || [];
21730
- setBridgeChains(chains);
21731
- return chains;
21732
- } catch (e) {
21733
- console.warn("[LiFi] Failed to fetch chains:", e.message);
21734
- return [];
21735
- }
21506
+ const chains = Object.entries(CHAIN_ID_TO_SHORT_NAME).map(([id, shortName]) => ({
21507
+ id: Number(id),
21508
+ chainId: Number(id),
21509
+ name: shortName,
21510
+ displayName: shortName,
21511
+ chainType: "EVM"
21512
+ }));
21513
+ setBridgeChains(chains);
21514
+ return chains;
21736
21515
  }, []);
21737
21516
  const getBridgeQuote = useCallback(async (originChainId, destChainId, originTokenAddress, originTokenSymbol, originTokenDecimals, destTokenAddress, destTokenSymbol, amount, recipient, _originBridgeTokens, _destBridgeTokens, user, debugId = createDebugId(), attemptMeta = null) => {
21738
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
21517
+ var _a, _b, _c, _d, _e, _f, _g;
21739
21518
  const attemptId = (attemptMeta == null ? void 0 : attemptMeta.attemptId) ?? null;
21740
- const providerMode = (attemptMeta == null ? void 0 : attemptMeta.providerMode) || "auto";
21741
21519
  const isStillCurrent = () => {
21742
21520
  if (!(attemptMeta == null ? void 0 : attemptMeta.isStillCurrent)) return true;
21743
21521
  try {
@@ -21750,41 +21528,6 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21750
21528
  setBridgeError(null);
21751
21529
  const resolvedOriginAddress = !originTokenAddress || originTokenAddress === "native" || originTokenAddress.length < 10 ? NATIVE_TOKEN_ADDRESS : originTokenAddress;
21752
21530
  const resolvedDestAddress = !destTokenAddress || destTokenAddress.length < 10 ? NATIVE_TOKEN_ADDRESS : destTokenAddress;
21753
- const fromAddressForFallback = user || recipient;
21754
- const requestAcrossQuote = async () => getAcrossQuote({
21755
- originChainId,
21756
- destChainId,
21757
- originTokenAddress: resolvedOriginAddress,
21758
- originTokenSymbol,
21759
- destTokenAddress: resolvedDestAddress,
21760
- destTokenSymbol,
21761
- amount,
21762
- recipient,
21763
- fromAddress: fromAddressForFallback,
21764
- debugId,
21765
- attemptId,
21766
- attemptMeta,
21767
- acrossApi: acrossApiRef.current
21768
- });
21769
- if (providerMode === "across-only") {
21770
- try {
21771
- const acrossQuote = await requestAcrossQuote();
21772
- if (!isStillCurrent()) {
21773
- console.log("[Across] Dropping stale fallback quote — attempt no longer current", { debugId, attemptId });
21774
- return acrossQuote;
21775
- }
21776
- setBridgeQuote(acrossQuote);
21777
- setBridgeStatus("idle");
21778
- setBridgeError(null);
21779
- return acrossQuote;
21780
- } catch (acrossError) {
21781
- console.warn("[Across] Fallback quote failed:", acrossError.message, { debugId, attemptId });
21782
- setBridgeQuote(null);
21783
- setBridgeError(acrossError.message);
21784
- setBridgeStatus("error");
21785
- return null;
21786
- }
21787
- }
21788
21531
  try {
21789
21532
  const normalizedOriginSymbol = (originTokenSymbol || "").toUpperCase();
21790
21533
  const normalizedDestSymbol = (destTokenSymbol || "").toUpperCase();
@@ -21793,25 +21536,8 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21793
21536
  const isSwap = !isSameToken;
21794
21537
  const destDecimals = 6;
21795
21538
  const toAmountRaw = BigInt(Math.ceil(parseFloat(amount) * Math.pow(10, destDecimals))).toString();
21796
- const fromAmountRaw = BigInt(Math.floor(parseFloat(amount) * Math.pow(10, originTokenDecimals || 18))).toString();
21797
- const useExactOutputQuote = true;
21798
21539
  const fromAddress = user || recipient;
21799
- const params = new URLSearchParams({
21800
- fromChain: originChainId.toString(),
21801
- toChain: destChainId.toString(),
21802
- fromToken: resolvedOriginAddress,
21803
- toToken: resolvedDestAddress,
21804
- fromAddress,
21805
- toAddress: recipient,
21806
- integrator: LIFI_INTEGRATOR,
21807
- fee: "0",
21808
- slippage: "0.005",
21809
- order: "CHEAPEST"
21810
- });
21811
- if (useExactOutputQuote) {
21812
- params.set("toAmount", toAmountRaw);
21813
- }
21814
- console.log("[LiFi] Requesting quote:", {
21540
+ console.log("[Bridge] Requesting server route:", {
21815
21541
  debugId,
21816
21542
  fromChain: originChainId,
21817
21543
  toChain: destChainId,
@@ -21819,77 +21545,92 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21819
21545
  toToken: `${destTokenSymbol} (${resolvedDestAddress.slice(0, 10)}...)`,
21820
21546
  recipient,
21821
21547
  fromAddress,
21822
- requestedAmount: useExactOutputQuote ? toAmountRaw : fromAmountRaw,
21823
- quoteMode: useExactOutputQuote ? "toAmount" : "fromAmount",
21548
+ requestedAmount: toAmountRaw,
21549
+ quoteMode: "exactOutput",
21824
21550
  isSwap,
21825
21551
  isSameChain
21826
21552
  });
21827
- const endpoint = useExactOutputQuote ? "quote/toAmount" : "quote";
21828
- const response = await fetch(`${LIFI_API_URL}/${endpoint}?${params.toString()}`, {
21829
- headers,
21830
- signal: AbortSignal.timeout(2e4)
21553
+ const bridgeApi = bridgeApiRef.current;
21554
+ if (!(bridgeApi == null ? void 0 : bridgeApi.getBridgeRoute)) {
21555
+ throw new Error("Bridge routing service is not configured");
21556
+ }
21557
+ const route = await bridgeApi.getBridgeRoute({
21558
+ fromChainId: Number(originChainId),
21559
+ toChainId: Number(destChainId),
21560
+ fromToken: {
21561
+ address: resolvedOriginAddress,
21562
+ symbol: originTokenSymbol,
21563
+ decimals: Number(originTokenDecimals || 18)
21564
+ },
21565
+ toToken: {
21566
+ address: resolvedDestAddress,
21567
+ symbol: destTokenSymbol,
21568
+ decimals: destDecimals
21569
+ },
21570
+ amount: toAmountRaw,
21571
+ quoteMode: "exactOutput",
21572
+ fromAddress,
21573
+ recipient,
21574
+ slippage: "0.005"
21831
21575
  });
21832
- if (!response.ok) {
21833
- const errorData = await response.json().catch(() => ({}));
21834
- throw new Error(errorData.message || `Quote request failed (${response.status})`);
21835
- }
21836
- const quote = await response.json();
21837
- const estimate = quote.estimate || {};
21838
- const feeCosts = estimate.feeCosts || [];
21839
- const gasCosts = estimate.gasCosts || [];
21840
- const totalFee = feeCosts.reduce((sum, f2) => sum + parseFloat(f2.amountUSD || 0), 0) + gasCosts.reduce((sum, g) => sum + parseFloat(g.amountUSD || 0), 0);
21576
+ if (!(route == null ? void 0 : route.transactionRequest)) {
21577
+ throw new Error("Bridge route returned no executable transaction");
21578
+ }
21841
21579
  const parsedQuote = {
21842
21580
  debugId,
21843
- provider: "lifi",
21844
- raw: quote,
21581
+ provider: route.provider || "bridge",
21582
+ raw: route.raw || route,
21845
21583
  originChainId,
21846
21584
  destChainId,
21847
21585
  originChainName: CHAIN_ID_TO_SHORT_NAME[originChainId] || `Chain ${originChainId}`,
21848
21586
  destChainName: CHAIN_ID_TO_SHORT_NAME[destChainId] || `Chain ${destChainId}`,
21849
- originTokenSymbol: originTokenSymbol || ((_b = (_a = quote.action) == null ? void 0 : _a.fromToken) == null ? void 0 : _b.symbol) || "Unknown",
21587
+ originTokenSymbol: originTokenSymbol || ((_c = (_b = (_a = route.raw) == null ? void 0 : _a.action) == null ? void 0 : _b.fromToken) == null ? void 0 : _c.symbol) || "Unknown",
21850
21588
  originTokenAddress: resolvedOriginAddress,
21851
- inputAmount: estimate.fromAmountUSD ? `$${parseFloat(estimate.fromAmountUSD).toFixed(2)}` : ((_d = (_c = quote.action) == null ? void 0 : _c.fromToken) == null ? void 0 : _d.symbol) ? `${(parseFloat(quote.action.fromAmount) / Math.pow(10, quote.action.fromToken.decimals)).toFixed(4)} ${quote.action.fromToken.symbol}` : amount,
21852
- destTokenSymbol: destTokenSymbol || ((_f = (_e = quote.action) == null ? void 0 : _e.toToken) == null ? void 0 : _f.symbol) || "USDC",
21589
+ inputAmount: formatTokenAmount(route.fromAmount, originTokenDecimals || 18, originTokenSymbol),
21590
+ destTokenSymbol: destTokenSymbol || ((_f = (_e = (_d = route.raw) == null ? void 0 : _d.action) == null ? void 0 : _e.toToken) == null ? void 0 : _f.symbol) || "USDC",
21853
21591
  destTokenAddress: resolvedDestAddress,
21854
- outputAmount: estimate.toAmountMin ? (parseFloat(estimate.toAmountMin) / Math.pow(10, ((_h = (_g = quote.action) == null ? void 0 : _g.toToken) == null ? void 0 : _h.decimals) || 6)).toFixed(4) : amount,
21855
- bridgeFee: totalFee > 0 ? totalFee.toFixed(2) : "0",
21592
+ outputAmount: formatTokenAmount(route.toAmount || route.toAmountMin, destDecimals, ""),
21593
+ bridgeFee: Number(route.totalFeeUsd || 0).toFixed(2),
21856
21594
  bridgeFeeCurrency: "USD",
21857
- estimatedTime: estimate.executionDuration || 30,
21858
- steps: quote.includedSteps || [],
21859
- tool: quote.tool,
21860
- toolDetails: quote.toolDetails,
21595
+ estimatedTime: route.estimatedTimeSec || 30,
21596
+ steps: ((_g = route.raw) == null ? void 0 : _g.includedSteps) || [],
21597
+ tool: route.provider,
21598
+ toolDetails: { name: route.provider },
21861
21599
  isSwap,
21862
21600
  isSameChain,
21863
- tradeType: useExactOutputQuote ? "EXACT_OUTPUT" : "EXACT_INPUT",
21601
+ tradeType: "EXACT_OUTPUT",
21864
21602
  requestedRecipient: normalizeAddress(recipient),
21865
- effectiveRecipient: extractQuoteRecipient(quote),
21866
- // Li.Fi provides transactionRequest directly
21867
- transactionRequest: quote.transactionRequest,
21868
- approvalAddress: estimate.approvalAddress,
21603
+ effectiveRecipient: normalizeAddress(route.effectiveRecipient) || extractQuoteRecipient(route.raw || {}),
21604
+ transactionRequest: route.transactionRequest,
21605
+ approvalTxns: route.approvalTxns || [],
21606
+ approvalAddress: route.approvalAddress,
21607
+ fromAmountRaw: route.fromAmount,
21608
+ toAmountRaw: route.toAmount,
21609
+ toAmountMinRaw: route.toAmountMin,
21869
21610
  attemptId,
21870
21611
  selectionSnapshot: (attemptMeta == null ? void 0 : attemptMeta.selectionSnapshot) ?? null
21871
21612
  };
21872
- console.log("[LiFi] Quote response:", {
21613
+ console.log("[Bridge] Server route response:", {
21873
21614
  debugId,
21874
21615
  attemptId,
21875
- tool: quote.tool,
21616
+ provider: parsedQuote.provider,
21876
21617
  requestedRecipient: parsedQuote.requestedRecipient,
21877
21618
  effectiveRecipient: parsedQuote.effectiveRecipient,
21878
- approvalAddress: estimate.approvalAddress,
21879
- toAmount: estimate.toAmount,
21880
- toAmountMin: estimate.toAmountMin,
21881
- fromAmount: estimate.fromAmount,
21882
- executionDuration: estimate.executionDuration,
21883
- includedStepCount: ((_i = quote.includedSteps) == null ? void 0 : _i.length) || 0,
21884
- transactionRequest: quote.transactionRequest ? {
21885
- to: quote.transactionRequest.to,
21886
- chainId: quote.transactionRequest.chainId,
21887
- hasData: !!quote.transactionRequest.data,
21888
- hasValue: quote.transactionRequest.value !== void 0
21619
+ approvalAddress: parsedQuote.approvalAddress,
21620
+ approvalTxnCount: parsedQuote.approvalTxns.length,
21621
+ toAmount: route.toAmount,
21622
+ toAmountMin: route.toAmountMin,
21623
+ fromAmount: route.fromAmount,
21624
+ executionDuration: route.estimatedTimeSec,
21625
+ transactionRequest: route.transactionRequest ? {
21626
+ to: route.transactionRequest.to,
21627
+ chainId: route.transactionRequest.chainId,
21628
+ hasData: !!route.transactionRequest.data,
21629
+ hasValue: route.transactionRequest.value !== void 0
21889
21630
  } : null
21890
21631
  });
21891
21632
  if (!isStillCurrent()) {
21892
- console.log("[LiFi] Dropping stale quote result — attempt no longer current", { debugId, attemptId });
21633
+ console.log("[Bridge] Dropping stale quote result — attempt no longer current", { debugId, attemptId });
21893
21634
  return parsedQuote;
21894
21635
  }
21895
21636
  setBridgeQuote(parsedQuote);
@@ -21897,30 +21638,11 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21897
21638
  return parsedQuote;
21898
21639
  } catch (error) {
21899
21640
  const stillCurrent = isStillCurrent();
21900
- console.warn("[LiFi] Quote failed:", error.message, { debugId, attemptId, stillCurrent });
21641
+ console.warn("[Bridge] Route quote failed:", error.message, { debugId, attemptId, stillCurrent });
21901
21642
  if (!stillCurrent) {
21902
- console.log("[LiFi] Ignoring stale quote error");
21903
- return null;
21904
- }
21905
- if (providerMode === "lifi-only") {
21906
- setBridgeQuote(null);
21907
- setBridgeError(error.message);
21908
- setBridgeStatus("error");
21643
+ console.log("[Bridge] Ignoring stale quote error");
21909
21644
  return null;
21910
21645
  }
21911
- try {
21912
- const acrossQuote = await requestAcrossQuote();
21913
- if (!isStillCurrent()) {
21914
- console.log("[Across] Dropping stale fallback quote — attempt no longer current", { debugId, attemptId });
21915
- return acrossQuote;
21916
- }
21917
- setBridgeQuote(acrossQuote);
21918
- setBridgeStatus("idle");
21919
- setBridgeError(null);
21920
- return acrossQuote;
21921
- } catch (acrossError) {
21922
- console.warn("[Across] Fallback quote failed:", acrossError.message, { debugId, attemptId });
21923
- }
21924
21646
  setBridgeQuote(null);
21925
21647
  setBridgeError(error.message);
21926
21648
  setBridgeStatus("error");
@@ -21928,7 +21650,7 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21928
21650
  }
21929
21651
  }, []);
21930
21652
  const executeBridge = useCallback(async (quote, walletClient, onProgress) => {
21931
- var _a, _b;
21653
+ var _a, _b, _c, _d;
21932
21654
  setBridgeStatus("bridging");
21933
21655
  setBridgeError(null);
21934
21656
  try {
@@ -21937,80 +21659,46 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
21937
21659
  if (!txRequest) {
21938
21660
  throw new Error("Invalid quote: no transaction data");
21939
21661
  }
21940
- if (quote.provider === "across") {
21941
- const approvalTxns = quote.approvalTxns || ((_b = quote.raw) == null ? void 0 : _b.approvalTxns) || [];
21942
- for (const approvalTxn of approvalTxns) {
21943
- if (!(approvalTxn == null ? void 0 : approvalTxn.to) || !(approvalTxn == null ? void 0 : approvalTxn.data)) continue;
21944
- onProgress == null ? void 0 : onProgress("approving", "Approving token spend...");
21945
- console.log("[Across] Sending approval tx:", {
21946
- debugId,
21947
- chainId: quote.originChainId,
21948
- to: approvalTxn.to
21949
- });
21950
- const approveTx = await walletClient.sendTransaction({
21951
- to: approvalTxn.to,
21952
- data: approvalTxn.data,
21953
- value: approvalTxn.value ? BigInt(approvalTxn.value) : 0n,
21954
- chainId: quote.originChainId
21955
- });
21956
- console.log("[Across] Approval tx submitted:", { debugId, approveTx });
21957
- onProgress == null ? void 0 : onProgress("approving", "Waiting for approval confirmation...");
21958
- await waitForTxReceipt(approveTx, quote.originChainId);
21959
- }
21960
- onProgress == null ? void 0 : onProgress("signing", "Sending bridge transaction...");
21961
- console.log("[Across] Sending bridge tx:", {
21662
+ const approvalTxns = quote.approvalTxns || ((_b = quote.raw) == null ? void 0 : _b.approvalTxns) || [];
21663
+ for (const approvalTxn of approvalTxns) {
21664
+ if (!(approvalTxn == null ? void 0 : approvalTxn.to) || !(approvalTxn == null ? void 0 : approvalTxn.data)) continue;
21665
+ onProgress == null ? void 0 : onProgress("approving", "Approving token spend...");
21666
+ console.log("[Bridge] Sending provider approval tx:", {
21962
21667
  debugId,
21963
- chainId: quote.originChainId,
21964
- txTo: txRequest.to,
21965
- txChainId: txRequest.chainId,
21966
- hasData: !!txRequest.data,
21967
- value: txRequest.value || "0"
21968
- });
21969
- const txHash2 = await walletClient.sendTransaction({
21970
- to: txRequest.to,
21971
- data: txRequest.data,
21972
- value: txRequest.value ? BigInt(txRequest.value) : 0n,
21973
- chainId: quote.originChainId,
21974
- ...txRequest.gas ? { gas: BigInt(txRequest.gas) } : {}
21668
+ chainId: approvalTxn.chainId || quote.originChainId,
21669
+ to: approvalTxn.to
21975
21670
  });
21976
- console.log("[Across] Bridge tx submitted:", {
21977
- debugId,
21978
- txHash: txHash2,
21979
- recipient: quote.requestedRecipient
21671
+ const approveTx = await walletClient.sendTransaction({
21672
+ to: approvalTxn.to,
21673
+ data: approvalTxn.data,
21674
+ value: approvalTxn.value ? BigInt(approvalTxn.value) : 0n,
21675
+ chainId: approvalTxn.chainId || quote.originChainId
21980
21676
  });
21981
- onProgress == null ? void 0 : onProgress("submitted", `Transaction submitted: ${txHash2.slice(0, 10)}...`);
21982
- onProgress == null ? void 0 : onProgress("confirming", "Waiting for bridge delivery...");
21983
- await pollAcrossStatus(txHash2, quote.originChainId, debugId);
21984
- setBridgeStatus("completed");
21985
- onProgress == null ? void 0 : onProgress("completed", "bridge complete!");
21986
- return { success: true, txHash: txHash2 };
21677
+ console.log("[Bridge] Approval tx submitted:", { debugId, approveTx });
21678
+ onProgress == null ? void 0 : onProgress("approving", "Approval submitted...");
21987
21679
  }
21988
- if (quote.approvalAddress && quote.originTokenAddress !== NATIVE_TOKEN_ADDRESS) {
21680
+ if (quote.approvalAddress && quote.originTokenAddress !== NATIVE_TOKEN_ADDRESS && approvalTxns.length === 0) {
21989
21681
  onProgress == null ? void 0 : onProgress("approving", "Approving token spend...");
21990
- try {
21991
- const approveData = "0x095ea7b3" + quote.approvalAddress.slice(2).padStart(64, "0") + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
21992
- console.log("[LiFi] Sending approval tx:", {
21993
- debugId,
21994
- chainId: quote.originChainId,
21995
- token: quote.originTokenAddress,
21996
- approvalAddress: quote.approvalAddress
21997
- });
21998
- const approveTx = await walletClient.sendTransaction({
21999
- to: quote.originTokenAddress,
22000
- data: approveData,
22001
- chainId: quote.originChainId
22002
- });
22003
- console.log("[LiFi] Approval tx submitted:", { debugId, approveTx });
22004
- onProgress == null ? void 0 : onProgress("approving", "Waiting for approval confirmation...");
22005
- await new Promise((resolve) => setTimeout(resolve, 3e3));
22006
- } catch (e) {
22007
- console.warn("[LiFi] Approval failed, proceeding:", e.message);
22008
- }
21682
+ const approveData = buildApprovalData(quote.approvalAddress, quote.fromAmountRaw || ((_c = quote.raw) == null ? void 0 : _c.fromAmount));
21683
+ console.log("[Bridge] Sending spender approval tx:", {
21684
+ debugId,
21685
+ chainId: quote.originChainId,
21686
+ token: quote.originTokenAddress,
21687
+ approvalAddress: quote.approvalAddress
21688
+ });
21689
+ const approveTx = await walletClient.sendTransaction({
21690
+ to: quote.originTokenAddress,
21691
+ data: approveData,
21692
+ chainId: quote.originChainId
21693
+ });
21694
+ console.log("[Bridge] Approval tx submitted:", { debugId, approveTx });
21695
+ onProgress == null ? void 0 : onProgress("approving", "Approval submitted...");
22009
21696
  }
22010
21697
  const action = quote.isSwap ? "swap" : "bridge";
22011
21698
  onProgress == null ? void 0 : onProgress("signing", `Sending ${action} transaction...`);
22012
- console.log("[LiFi] Sending main tx:", {
21699
+ console.log("[Bridge] Sending main tx:", {
22013
21700
  debugId,
21701
+ provider: quote.provider,
22014
21702
  action,
22015
21703
  chainId: quote.originChainId,
22016
21704
  txTo: txRequest.to,
@@ -22022,30 +21710,43 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
22022
21710
  to: txRequest.to,
22023
21711
  data: txRequest.data,
22024
21712
  value: txRequest.value ? BigInt(txRequest.value) : 0n,
22025
- chainId: quote.originChainId,
22026
- ...txRequest.gasLimit ? { gas: BigInt(txRequest.gasLimit) } : {}
21713
+ chainId: txRequest.chainId || quote.originChainId,
21714
+ ...txRequest.gasLimit || txRequest.gas ? { gas: BigInt(txRequest.gasLimit || txRequest.gas) } : {}
22027
21715
  });
22028
- console.log("[LiFi] Main tx submitted:", {
21716
+ console.log("[Bridge] Main tx submitted:", {
22029
21717
  debugId,
22030
21718
  txHash,
22031
21719
  quoteRequestedRecipient: quote == null ? void 0 : quote.requestedRecipient,
22032
- quoteEffectiveRecipient: quote == null ? void 0 : quote.effectiveRecipient,
22033
- sourceExplorer: txHash ? `https://scan.li.fi/tx/${txHash}` : null
21720
+ quoteEffectiveRecipient: quote == null ? void 0 : quote.effectiveRecipient
22034
21721
  });
22035
21722
  onProgress == null ? void 0 : onProgress("submitted", `Transaction submitted: ${txHash.slice(0, 10)}...`);
22036
- onProgress == null ? void 0 : onProgress("confirming", `Confirming ${action}...`);
22037
- const confirmed = await waitForTxReceipt(txHash, quote.originChainId);
22038
- if (!confirmed) {
22039
- if (!quote.isSameChain) {
22040
- onProgress == null ? void 0 : onProgress("confirming", "Waiting for bridge delivery...");
22041
- await pollLiFiStatus(txHash, quote.originChainId, quote.destChainId, debugId);
21723
+ if (quote.paymentId && ((_d = bridgeApiRef.current) == null ? void 0 : _d.trackBridge)) {
21724
+ try {
21725
+ await bridgeApiRef.current.trackBridge({
21726
+ paymentId: quote.paymentId,
21727
+ provider: quote.provider,
21728
+ sourceChainId: quote.originChainId,
21729
+ sourceTxHash: txHash
21730
+ });
21731
+ console.log("[Bridge] Tracking registered:", {
21732
+ debugId,
21733
+ paymentId: quote.paymentId,
21734
+ provider: quote.provider,
21735
+ sourceChainId: quote.originChainId,
21736
+ sourceTxHash: txHash
21737
+ });
21738
+ } catch (trackError) {
21739
+ console.warn("[Bridge] Track request failed; deposit polling will continue:", {
21740
+ debugId,
21741
+ error: trackError.message
21742
+ });
22042
21743
  }
22043
21744
  }
22044
21745
  setBridgeStatus("completed");
22045
- onProgress == null ? void 0 : onProgress("completed", `${action} complete!`);
21746
+ onProgress == null ? void 0 : onProgress("completed", `${action} submitted!`);
22046
21747
  return { success: true, txHash };
22047
21748
  } catch (error) {
22048
- console.error("[LiFi] Execution failed:", { debugId: quote == null ? void 0 : quote.debugId, error });
21749
+ console.error("[Bridge] Execution failed:", { debugId: quote == null ? void 0 : quote.debugId, error });
22049
21750
  setBridgeError(error.message);
22050
21751
  setBridgeStatus("error");
22051
21752
  onProgress == null ? void 0 : onProgress("error", error.message);
@@ -22189,45 +21890,6 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
22189
21890
  return { success: false, error: error.message };
22190
21891
  }
22191
21892
  }, []);
22192
- const waitForTxReceipt = async (txHash, chainId) => {
22193
- var _a, _b;
22194
- const ALCHEMY_KEY = "YWG990wOlIikc1tU7-WWTepfU8d1f4dp";
22195
- const slugs = {
22196
- 1: "eth-mainnet",
22197
- 8453: "base-mainnet",
22198
- 42161: "arb-mainnet",
22199
- 137: "polygon-mainnet",
22200
- 10: "opt-mainnet",
22201
- 56: "bnb-mainnet",
22202
- 43114: "avax-mainnet",
22203
- 42220: "celo-mainnet",
22204
- 59144: "linea-mainnet",
22205
- 81457: "blast-mainnet",
22206
- 534352: "scroll-mainnet",
22207
- 324: "zksync-mainnet",
22208
- 80094: "berachain-mainnet",
22209
- 2741: "abstract-mainnet",
22210
- 130: "unichain-mainnet"
22211
- };
22212
- const slug = slugs[chainId];
22213
- if (!slug) return false;
22214
- for (let i = 0; i < 30; i++) {
22215
- try {
22216
- const res = await fetch(`https://${slug}.g.alchemy.com/v2/${ALCHEMY_KEY}`, {
22217
- method: "POST",
22218
- headers: { "Content-Type": "application/json" },
22219
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_getTransactionReceipt", params: [txHash] }),
22220
- signal: AbortSignal.timeout(5e3)
22221
- }).then((r) => r.json());
22222
- if (((_a = res.result) == null ? void 0 : _a.status) === "0x1") return true;
22223
- if (((_b = res.result) == null ? void 0 : _b.status) === "0x0") throw new Error("Transaction reverted on-chain");
22224
- } catch (e) {
22225
- if (e.message.includes("reverted")) throw e;
22226
- }
22227
- await new Promise((r) => setTimeout(r, 2e3));
22228
- }
22229
- return false;
22230
- };
22231
21893
  const pollLiFiStatus = async (txHash, fromChain, toChain, debugId) => {
22232
21894
  var _a, _b, _c, _d, _e;
22233
21895
  let lastLoggedPhase = null;
@@ -22235,7 +21897,7 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
22235
21897
  try {
22236
21898
  const res = await fetch(
22237
21899
  `${LIFI_API_URL}/status?txHash=${txHash}&fromChain=${fromChain}&toChain=${toChain}`,
22238
- { headers, signal: AbortSignal.timeout(1e4) }
21900
+ { headers: { "Content-Type": "application/json" }, signal: AbortSignal.timeout(1e4) }
22239
21901
  );
22240
21902
  if (res.ok) {
22241
21903
  const status = await res.json();
@@ -22283,45 +21945,6 @@ const useBridge = (apiUrl, publicKeyOrApiKey, apiSecret = null) => {
22283
21945
  }
22284
21946
  return false;
22285
21947
  };
22286
- const pollAcrossStatus = async (txHash, originChainId, debugId) => {
22287
- var _a, _b, _c;
22288
- let lastStatus = null;
22289
- for (let i = 0; i < 60; i++) {
22290
- try {
22291
- const acrossApi = acrossApiRef.current;
22292
- if (!(acrossApi == null ? void 0 : acrossApi.getAcrossStatus)) {
22293
- throw new Error("Across server proxy is not configured");
22294
- }
22295
- const status = await acrossApi.getAcrossStatus({
22296
- originChainId: String(originChainId),
22297
- depositTxHash: txHash
22298
- });
22299
- const statusValue = status.status || status.fillStatus || ((_a = status.deposit) == null ? void 0 : _a.status) || "unknown";
22300
- if (statusValue !== lastStatus || i === 0 || (i + 1) % 10 === 0) {
22301
- console.log("[Across] Status checkpoint:", {
22302
- debugId,
22303
- attempt: i + 1,
22304
- sourceTxHash: txHash,
22305
- status: statusValue,
22306
- fillTxHash: status.fillTxHash || ((_b = status.deposit) == null ? void 0 : _b.fillTxHash),
22307
- destinationChainId: status.destinationChainId || ((_c = status.deposit) == null ? void 0 : _c.destinationChainId)
22308
- });
22309
- lastStatus = statusValue;
22310
- }
22311
- const normalized = String(statusValue).toLowerCase();
22312
- if (normalized.includes("filled") || normalized.includes("complete") || normalized === "filled" || status.filled === true) {
22313
- return true;
22314
- }
22315
- if (normalized.includes("failed") || normalized.includes("expired")) {
22316
- throw new Error("Across bridge transaction failed");
22317
- }
22318
- } catch (e) {
22319
- if (e.message.includes("failed")) throw e;
22320
- }
22321
- await new Promise((r) => setTimeout(r, 3e3));
22322
- }
22323
- return false;
22324
- };
22325
21948
  const resetBridge = useCallback(() => {
22326
21949
  setBridgeStatus("idle");
22327
21950
  setBridgeQuote(null);
@@ -22353,8 +21976,7 @@ const COINGECKO_CHAIN_SLUGS = {
22353
21976
  42220: "celo"
22354
21977
  };
22355
21978
  const LIFI_HEADERS = {
22356
- "Content-Type": "application/json",
22357
- ...{ "x-lifi-api-key": LIFI_API_KEY }
21979
+ "Content-Type": "application/json"
22358
21980
  };
22359
21981
  const TOKEN_LIST_TTL = 10 * 60 * 1e3;
22360
21982
  const WALLET_TOKEN_CACHE_TTL_MS = 30 * 1e3;
@@ -23339,6 +22961,36 @@ const BROKEN_TOKENS_BY_CHAIN = {
23339
22961
  "USDT"
23340
22962
  ]
23341
22963
  };
22964
+ const ACROSS_SUPPORTED_USDC_SOURCE_CHAINS = /* @__PURE__ */ new Set([
22965
+ 1,
22966
+ 10,
22967
+ 130,
22968
+ 137,
22969
+ 143,
22970
+ 232,
22971
+ 480,
22972
+ 999,
22973
+ 1868,
22974
+ 42161,
22975
+ 534352,
22976
+ 57073,
22977
+ 59144,
22978
+ 324
22979
+ ]);
22980
+ const ACROSS_SUPPORTED_USDT_SOURCE_CHAINS = /* @__PURE__ */ new Set([
22981
+ 1,
22982
+ 10,
22983
+ 130,
22984
+ 137,
22985
+ 143,
22986
+ 999,
22987
+ 1868,
22988
+ 42161,
22989
+ 534352,
22990
+ 59144,
22991
+ 57073,
22992
+ 324
22993
+ ]);
23342
22994
  const DIRECT_EVM_PAYMENT_CHAINS = /* @__PURE__ */ new Set([
23343
22995
  "ethereum",
23344
22996
  "bsc",
@@ -24455,7 +24107,8 @@ const CoinleyPaymentInternal = ({
24455
24107
  const isSolanaNetwork2 = (selectedNetwork == null ? void 0 : selectedNetwork.shortName) === "solana" || (selectedNetwork == null ? void 0 : selectedNetwork.chainType) === "solana";
24456
24108
  const useGenericMobileTokenList = isMobile && showMobileWalletPicker && !!selectedMobileWallet && !connectedWalletType;
24457
24109
  useEffect(() => {
24458
- if (!useGenericMobileTokenList || !(selectedNetwork == null ? void 0 : selectedNetwork.isExtraNetwork)) {
24110
+ var _a2;
24111
+ if (!useGenericMobileTokenList || !(selectedNetwork == null ? void 0 : selectedNetwork.isExtraNetwork) || !((_a2 = paymentFlow.api) == null ? void 0 : _a2.getBridgeTokens)) {
24459
24112
  setMobileCatalogTokens([]);
24460
24113
  return;
24461
24114
  }
@@ -24467,30 +24120,21 @@ const CoinleyPaymentInternal = ({
24467
24120
  return;
24468
24121
  }
24469
24122
  let cancelled = false;
24470
- const lifiHeaders = { "Content-Type": "application/json", ...{ "x-lifi-api-key": LIFI_API_KEY } };
24471
24123
  const shortName = selectedNetwork.shortName;
24472
24124
  const networkName = selectedNetwork.name;
24473
24125
  const stableSymbols = /* @__PURE__ */ new Set(["USDC", "USDT", "DAI"]);
24474
24126
  (async () => {
24475
- var _a2, _b;
24476
24127
  try {
24477
- const params = new URLSearchParams({ chains: chainId.toString(), minPriceUSD: "0" });
24478
- const res = await fetch(`${LIFI_API_URL}/tokens?${params.toString()}`, {
24479
- headers: lifiHeaders,
24480
- signal: AbortSignal.timeout(15e3)
24481
- });
24482
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
24483
- const data = await res.json();
24484
- const chainTokens = ((_a2 = data == null ? void 0 : data.tokens) == null ? void 0 : _a2[chainId]) || ((_b = data == null ? void 0 : data.tokens) == null ? void 0 : _b[String(chainId)]) || [];
24128
+ const chainTokens = await paymentFlow.api.getBridgeTokens(chainId);
24485
24129
  const entries = chainTokens.map((t) => {
24486
24130
  const isStable = stableSymbols.has((t.symbol || "").toUpperCase());
24487
- const isNative = t.address === NATIVE_TOKEN_ADDRESS;
24131
+ const isNative = t.address === NATIVE_TOKEN_ADDRESS || t.address === "native";
24488
24132
  return {
24489
- id: `mobile-lifi-${chainId}-${t.address}`,
24133
+ id: `mobile-bridge-${chainId}-${t.address}`,
24490
24134
  symbol: t.symbol,
24491
- name: t.name,
24135
+ name: t.name || t.symbol,
24492
24136
  contractAddress: isNative ? "native" : t.address,
24493
- decimals: t.decimals,
24137
+ decimals: t.decimals || 18,
24494
24138
  isStablecoin: isStable,
24495
24139
  isSwapToken: !isStable,
24496
24140
  balance: null,
@@ -24505,13 +24149,13 @@ const CoinleyPaymentInternal = ({
24505
24149
  setMobileCatalogTokens(entries);
24506
24150
  }
24507
24151
  } catch (err) {
24508
- console.warn("[Mobile] Li.Fi token catalog fetch failed:", err.message);
24152
+ console.warn("[Mobile] Bridge token catalog fetch failed:", err.message);
24509
24153
  }
24510
24154
  })();
24511
24155
  return () => {
24512
24156
  cancelled = true;
24513
24157
  };
24514
- }, [useGenericMobileTokenList, selectedNetwork == null ? void 0 : selectedNetwork.isExtraNetwork, selectedNetwork == null ? void 0 : selectedNetwork.chainId, selectedNetwork == null ? void 0 : selectedNetwork.shortName, selectedNetwork == null ? void 0 : selectedNetwork.name]);
24158
+ }, [useGenericMobileTokenList, selectedNetwork == null ? void 0 : selectedNetwork.isExtraNetwork, selectedNetwork == null ? void 0 : selectedNetwork.chainId, selectedNetwork == null ? void 0 : selectedNetwork.shortName, selectedNetwork == null ? void 0 : selectedNetwork.name, paymentFlow.api]);
24515
24159
  const availableTokens = useMemo(() => {
24516
24160
  if (!selectedNetwork) return [];
24517
24161
  const networkTokens = [];
@@ -27005,4 +26649,4 @@ export {
27005
26649
  isFeatureEnabled as i,
27006
26650
  logo as l
27007
26651
  };
27008
- //# sourceMappingURL=CoinleyPayment-Bj4u9uQh.js.map
26652
+ //# sourceMappingURL=CoinleyPayment-pbTQ15wF.js.map