From db17923724fd712c226b18f624b21afbd26fdf40 Mon Sep 17 00:00:00 2001 From: Cardinal Date: Fri, 26 Jun 2026 13:22:50 +0200 Subject: [PATCH 1/3] Route all stamp purchases through Relay only Remove SushiSwapStampsRouter and direct BZZ registry flows that MetaMask flags as malicious, consolidating quotes and execution on Relay for every chain and token. --- src/app/components/CustomQuotes.ts | 3 +- src/app/components/RelayQuotes.ts | 162 ------- src/app/components/SushiQuotes.ts | 679 --------------------------- src/app/components/SwapComponent.tsx | 528 ++++----------------- src/app/components/TokenUtils.ts | 44 +- src/app/components/constants.ts | 168 +------ 6 files changed, 96 insertions(+), 1488 deletions(-) delete mode 100644 src/app/components/SushiQuotes.ts diff --git a/src/app/components/CustomQuotes.ts b/src/app/components/CustomQuotes.ts index 219652e..4febf6c 100644 --- a/src/app/components/CustomQuotes.ts +++ b/src/app/components/CustomQuotes.ts @@ -10,5 +10,4 @@ export { ChainId } from '@lifi/sdk'; // by the Relay API implementation in RelayQuotes.ts // // Current architecture: -// 1. Direct BZZ purchases → handleDirectBzzTransactions in SwapComponent.tsx -// 2. Cross-chain swaps → Relay API via RelayQuotes.ts +// All stamp purchases (same-chain and cross-chain) → Relay API via RelayQuotes.ts diff --git a/src/app/components/RelayQuotes.ts b/src/app/components/RelayQuotes.ts index 175cc1d..f3ee6fb 100644 --- a/src/app/components/RelayQuotes.ts +++ b/src/app/components/RelayQuotes.ts @@ -9,14 +9,8 @@ import { RELAY_STATUS_CHECK_INTERVAL_MS, RELAY_STATUS_MAX_ATTEMPTS, TRANSACTION_TIMEOUT_MS, - RELAY_BRIDGE_TOKEN_ON_GNOSIS, - RELAY_BRIDGE_TOKEN_DECIMALS, - RELAY_BRIDGE_TOKEN_SYMBOL, - SUSHI_STAMPS_ROUTER_ADDRESS, - SUSHI_STAMPS_ROUTER_ABI, } from './constants'; import { performWithRetry, getGnosisPublicClient } from './utils'; -import { getSushiQuote } from './SushiQuotes'; import { getPollingInterval } from '@/app/wagmi'; // Relay API Error Codes and Messages @@ -839,162 +833,6 @@ const monitorRelayStatus = async ( throw new Error(`Operation timed out for step ${stepId} after ${maxAttempts} attempts`); }; -/** - * Cross-chain flow: bridge source token → RELAY_BRIDGE_TOKEN (USDC) on Gnosis via Relay, - * then atomically swap USDC → BZZ and create/top-up a Swarm stamp via SushiSwapStampsRouter. - * - * Why: Relay has reliable routes to USDC on every major chain; routing directly to BZZ is - * fragile. The existing SushiSwapStampsRouter already handles USDC → BZZ → stamp on-chain. - * - * Relay delivers USDC to its Multicaller which executes two destination txs atomically: - * 1. USDC.approve(sushiRouter, maxUsdcIn) - * 2. sushiRouter.createBatch / topUp(path, maxUsdcIn, bzzOut, params) - */ -export const getRelayCrossChainWithSushiQuote = async ({ - selectedChainId, - fromToken, - address, - bzzAmount, - nodeAddress, - swarmConfig, - topUpBatchId, - setEstimatedTime, - isForEstimation = false, - slippagePercent, -}: RelayQuoteParams) => { - console.log( - `🌉 Cross-chain via USDC+Sushi – ${isForEstimation ? 'estimating' : 'executing'}…` - ); - - // ── Step 1: Sushi quote for bridge token → BZZ ────────────────────────────── - const sushiQuote = await getSushiQuote({ - fromToken: RELAY_BRIDGE_TOKEN_ON_GNOSIS, - bzzAmount, - slippagePercent: slippagePercent ?? DEFAULT_SLIPPAGE, - tokenSymbol: RELAY_BRIDGE_TOKEN_SYMBOL, - tokenDecimals: RELAY_BRIDGE_TOKEN_DECIMALS, - tokenPriceUsd: 1.0, // USDC ≈ $1 – used only for the internal USD display of the Sushi leg - }); - - const maxBridgeTokenIn = sushiQuote.maxAmountIn; // includes slippage buffer - - console.log(`🍣 Sushi quote: need ${maxBridgeTokenIn.toString()} ${RELAY_BRIDGE_TOKEN_SYMBOL} for ${bzzAmount} BZZ`); - - // ── Step 2: Encode SushiRouter calldata ───────────────────────────────────── - let routerCallData: string; - if (topUpBatchId) { - routerCallData = encodeFunctionData({ - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'topUp', - args: [ - sushiQuote.route.path, - maxBridgeTokenIn, - BigInt(bzzAmount), - topUpBatchId as `0x${string}`, - swarmConfig.swarmBatchInitialBalance, - ], - }); - } else { - routerCallData = encodeFunctionData({ - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'createBatch', - args: [ - sushiQuote.route.path, - maxBridgeTokenIn, - BigInt(bzzAmount), - { - owner: address as `0x${string}`, - nodeAddress: nodeAddress as `0x${string}`, - initialBalancePerChunk: swarmConfig.swarmBatchInitialBalance, - depth: swarmConfig.swarmBatchDepth, - bucketDepth: swarmConfig.swarmBatchBucketDepth, - nonce: swarmConfig.swarmBatchNonce, - immutable_: swarmConfig.swarmBatchImmutable, - }, - ], - }); - } - - // ── Step 3: Encode ERC-20 approval (exact amount; Multicaller is the caller) ─ - const approvalData = encodeFunctionData({ - abi: parseAbi(['function approve(address spender, uint256 amount) external returns (bool)']), - functionName: 'approve', - args: [SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, maxBridgeTokenIn], - }); - - const txs = [ - { to: RELAY_BRIDGE_TOKEN_ON_GNOSIS, value: '0', data: approvalData }, - { to: SUSHI_STAMPS_ROUTER_ADDRESS, value: '0', data: routerCallData }, - ]; - - // ── Step 4: Gas top-up on Gnosis ───────────────────────────────────────────── - const hasEnoughGas = await checkGnosisGasBalance(address); - const shouldTopupGas = !hasEnoughGas; - console.log(`⛽ Gas top-up: ${shouldTopupGas ? 'ENABLED' : 'DISABLED'}`); - - // ── Step 5: Relay quote to bridge source token → USDC on Gnosis ───────────── - const relayQuoteRequest: RelayQuoteRequest = { - user: address, - recipient: address, - originChainId: selectedChainId, - destinationChainId: ChainId.DAI, - originCurrency: fromToken, - destinationCurrency: RELAY_BRIDGE_TOKEN_ON_GNOSIS, - amount: maxBridgeTokenIn.toString(), - tradeType: 'EXACT_OUTPUT', // deliver exactly maxBridgeTokenIn USDC - txs, - slippageTolerance: Math.round((slippagePercent ?? DEFAULT_SLIPPAGE) * 100).toString(), - refundOnOrigin: true, - topupGas: shouldTopupGas, - ...(shouldTopupGas && { topupGasAmount: GAS_TOPUP_AMOUNT_USD }), - }; - - const relayQuoteResponse = await performWithRetry( - async () => { - console.log('🌐 Relay cross-chain USDC quote request:', relayQuoteRequest); - const response = await fetch('https://api.relay.link/quote', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(relayQuoteRequest), - }); - if (!response.ok) { - const errorText = await response.text(); - const { userMessage, errorCode } = parseRelayError(errorText); - const err = new Error(userMessage); - (err as any).relayErrorCode = errorCode; - (err as any).originalError = errorText; - throw err; - } - const data = await response.json(); - console.log('✅ Relay USDC quote response:', data); - return data as RelayQuoteResponse; - }, - `getRelayCrossChainWithSushiQuote-${isForEstimation ? 'estimation' : 'execution'}`, - undefined, - isForEstimation ? 3 : 5, - 500 - ); - - const totalAmountUSD = Number(relayQuoteResponse.details.currencyIn.amountUsd || 0); - - if (setEstimatedTime && relayQuoteResponse.details.timeEstimate) { - setEstimatedTime(Math.ceil(relayQuoteResponse.details.timeEstimate)); - } - - console.log( - `✅ Cross-chain USDC+Sushi quote: $${totalAmountUSD.toFixed(2)}, steps: ${relayQuoteResponse.steps.length}` - ); - - return { - totalAmountUSD, - relayQuoteResponse, - steps: relayQuoteResponse.steps, - estimatedTime: relayQuoteResponse.details.timeEstimate, - isGnosisOnly: false, - selectedChainId, - }; -}; - /** * Unified function that replaces the old modular quote system * Uses Relay API for both price estimation and execution diff --git a/src/app/components/SushiQuotes.ts b/src/app/components/SushiQuotes.ts deleted file mode 100644 index 46206ab..0000000 --- a/src/app/components/SushiQuotes.ts +++ /dev/null @@ -1,679 +0,0 @@ -import { parseAbi, encodePacked, getAddress, parseUnits } from 'viem'; -import { - GNOSIS_BZZ_ADDRESS, - GNOSIS_WXDAI_ADDRESS, - SUSHI_STAMPS_ROUTER_ADDRESS, - SUSHI_STAMPS_ROUTER_ABI, - SUSHI_FACTORY_ADDRESS, - SUSHI_FACTORY_ABI, - BZZ_USDC_POOL_ADDRESS, - GNOSIS_USDC_ADDRESS, - DEFAULT_SLIPPAGE, - TRANSACTION_TIMEOUT_MS, -} from './constants'; -import { getGnosisPublicClient, performWithRetry } from './utils'; -import { getPollingInterval } from '@/app/wagmi'; - -// ─── Types ─────────────────────────────────────────────────────────────────── - -export interface SushiRouteInfo { - /** Encoded path for exactOutput: BZZ ++ fee ++ [mid ++ fee]* ++ tokenIn */ - path: `0x${string}`; - /** Whether tokenIn is native xDAI (uses createBatchNative / topUpNative) */ - isNative: boolean; - /** Pool fee tier(s) used in the path */ - fees: number[]; - /** Human-readable route description */ - description: string; -} - -export interface SushiQuoteResult { - /** Amount of input tokens required (including slippage buffer) */ - maxAmountIn: bigint; - /** Exact amount without slippage (from Quoter) */ - amountInBeforeSlippage: bigint; - /** Approximate USD cost (amountIn × tokenPriceUsd) */ - totalAmountUSD: number; - /** The route used */ - route: SushiRouteInfo; - /** tokenIn address (address(0) for native xDAI) */ - tokenIn: string; - /** tokenIn symbol for display */ - tokenInSymbol: string; - /** tokenIn decimals */ - tokenInDecimals: number; -} - -export interface SushiQuoteParams { - /** Hex address of the input token (address(0) or '0x0' for native xDAI) */ - fromToken: string; - /** Exact BZZ amount needed (= swarmBatchTotal) */ - bzzAmount: string; - /** Slippage as percentage (e.g. 5 = 5%) */ - slippagePercent?: number; - /** Token symbol for display */ - tokenSymbol?: string; - /** Token decimals */ - tokenDecimals?: number; - /** Token USD price (used to compute totalAmountUSD) */ - tokenPriceUsd?: number; -} - -export interface SushiExecuteParams extends SushiQuoteParams { - /** Caller's wallet address */ - address: string; - /** swarm config used to build stamp params */ - swarmConfig: any; - /** Batch ID to top up (undefined = create new batch) */ - topUpBatchId?: string; - /** Node address for new batches */ - nodeAddress: string; - /** wagmi walletClient */ - walletClient: any; - /** wagmi publicClient */ - publicClient: any; - /** Pre-computed quote (if already fetched) */ - quote?: SushiQuoteResult; - /** Callback for status updates */ - setStatusMessage: (status: any) => void; - onTransactionConfirmed?: () => void; -} - -// ─── Constants ──────────────────────────────────────────────────────────────── - -const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; - -/** - * Common fee tiers to try when auto-discovering pools (SushiSwap V3). - * Order matters — try the most common first. - */ -const FEE_TIERS = [3000, 500, 10000, 100] as const; - -/** Minimal ABI for reading the fee tier directly from a V3 pool contract. */ -const POOL_FEE_ABI = parseAbi(['function fee() external view returns (uint24)']); - -/** V3 pool liquidity; pools can be deployed with no active LPs — Quoter then reverts. */ -const POOL_LIQUIDITY_ABI = parseAbi(['function liquidity() external view returns (uint128)']); - -async function v3PoolHasLiquidity(poolAddress: string): Promise { - try { - const { client } = getGnosisPublicClient(); - const liq = await client.readContract({ - address: poolAddress as `0x${string}`, - abi: POOL_LIQUIDITY_ABI, - functionName: 'liquidity', - }); - return liq > 0n; - } catch { - return false; - } -} - -/** - * Known pool addresses for tokens that have a direct BZZ pool. - * We store only the address — the fee is read from the pool contract at - * runtime so we never hardcode an assumption about the fee tier. - */ -const KNOWN_BZZ_POOL_ADDRESSES: Record = { - [GNOSIS_USDC_ADDRESS.toLowerCase()]: BZZ_USDC_POOL_ADDRESS, -}; - -/** Runtime cache: normalised token address → { pool, fee } */ -const bzzPoolCache: Record = {}; - -// ─── Pool Discovery ────────────────────────────────────────────────────────── - -/** - * Finds a direct BZZ pool for `tokenIn` on SushiSwap V3 (Gnosis). - * - * Strategy: - * 1. Return the runtime cache if already resolved. - * 2. If a known pool address exists for this token, read its fee() directly - * from the pool contract — avoids assuming the wrong fee tier. - * 3. Fall back to scanning factory.getPool() across all common fee tiers. - */ -async function findDirectBzzPool( - tokenIn: string -): Promise<{ pool: string; fee: number } | null> { - const normalised = tokenIn.toLowerCase(); - - if (bzzPoolCache[normalised]) { - return bzzPoolCache[normalised]; - } - - const { client } = getGnosisPublicClient(); - - // ── Strategy 1: known pool address → read actual fee from contract ───────── - const knownPoolAddress = KNOWN_BZZ_POOL_ADDRESSES[normalised]; - if (knownPoolAddress && knownPoolAddress !== ZERO_ADDRESS) { - try { - if (!(await v3PoolHasLiquidity(knownPoolAddress))) { - console.warn('⚠️ Known BZZ pool has zero liquidity, falling back to factory scan'); - } else { - const fee = await client.readContract({ - address: knownPoolAddress as `0x${string}`, - abi: POOL_FEE_ABI, - functionName: 'fee', - }); - const result = { pool: knownPoolAddress, fee: Number(fee) }; - bzzPoolCache[normalised] = result; - console.log(`🍣 Pool fee for ${tokenIn}: ${Number(fee)} (${Number(fee) / 10000}%)`); - return result; - } - } catch { - console.warn('⚠️ Could not read known BZZ pool, falling back to factory scan'); - } - } - - // ── Strategy 2: scan factory for all fee tiers ──────────────────────────── - for (const fee of FEE_TIERS) { - try { - const pool = await client.readContract({ - address: SUSHI_FACTORY_ADDRESS as `0x${string}`, - abi: SUSHI_FACTORY_ABI, - functionName: 'getPool', - args: [tokenIn as `0x${string}`, GNOSIS_BZZ_ADDRESS as `0x${string}`, fee], - }); - - if (pool && pool !== ZERO_ADDRESS && (await v3PoolHasLiquidity(pool as string))) { - const result = { pool: pool as string, fee }; - bzzPoolCache[normalised] = result; - return result; - } - } catch { - // Try next fee tier. - } - } - - return null; -} - -/** Runtime cache for arbitrary token-pair pools (key = `tokenA:tokenB`). */ -const poolPairCache: Record = {}; - -/** - * Scans the SushiSwap V3 factory for any pool between `tokenA` and `tokenB` - * across all common fee tiers. Results are cached by normalised pair key. - */ -async function findPoolBetween( - tokenA: string, - tokenB: string -): Promise<{ pool: string; fee: number } | null> { - const key = [tokenA.toLowerCase(), tokenB.toLowerCase()].sort().join(':'); - - if (key in poolPairCache) { - return poolPairCache[key]; - } - - const { client } = getGnosisPublicClient(); - - for (const fee of FEE_TIERS) { - try { - const pool = await client.readContract({ - address: SUSHI_FACTORY_ADDRESS as `0x${string}`, - abi: SUSHI_FACTORY_ABI, - functionName: 'getPool', - args: [tokenA as `0x${string}`, tokenB as `0x${string}`, fee], - }); - - if (pool && pool !== ZERO_ADDRESS && (await v3PoolHasLiquidity(pool as string))) { - const result = { pool: pool as string, fee }; - poolPairCache[key] = result; - return result; - } - } catch { - // Try next fee tier. - } - } - - poolPairCache[key] = null; - return null; -} - -// ─── Path Encoding ──────────────────────────────────────────────────────────── - -/** - * Encodes a single-hop exactOutput path: BZZ ++ fee ++ tokenIn. - */ -function encodeSingleHopPath(tokenIn: string, fee: number): `0x${string}` { - return encodePacked( - ['address', 'uint24', 'address'], - [GNOSIS_BZZ_ADDRESS as `0x${string}`, fee, tokenIn as `0x${string}`] - ); -} - -/** - * Encodes a two-hop exactOutput path: BZZ ++ fee2 ++ mid ++ fee1 ++ tokenIn. - */ -function encodeTwoHopPath( - tokenIn: string, - fee1: number, - mid: string, - fee2: number -): `0x${string}` { - return encodePacked( - ['address', 'uint24', 'address', 'uint24', 'address'], - [ - GNOSIS_BZZ_ADDRESS as `0x${string}`, - fee2, - mid as `0x${string}`, - fee1, - tokenIn as `0x${string}`, - ] - ); -} - -// ─── Route Resolution ───────────────────────────────────────────────────────── - -/** - * All structurally valid routes (pools exist and have non-zero liquidity), best first. - */ -export async function findSushiRoutes(fromToken: string): Promise { - const routes: SushiRouteInfo[] = []; - - const isNativeXdai = - fromToken === ZERO_ADDRESS || - fromToken === '0x0' || - fromToken.toLowerCase() === ZERO_ADDRESS; - - const effectiveTokenIn = isNativeXdai ? GNOSIS_WXDAI_ADDRESS : fromToken; - - const directPool = await findDirectBzzPool(effectiveTokenIn); - if (directPool) { - const path = encodeSingleHopPath(effectiveTokenIn, directPool.fee); - routes.push({ - path, - isNative: isNativeXdai, - fees: [directPool.fee], - description: isNativeXdai - ? `xDAI → WXDAI → BZZ (single-hop, ${directPool.fee / 10000}% fee)` - : `Direct → BZZ (${directPool.fee / 10000}% fee)`, - }); - } - - if (effectiveTokenIn.toLowerCase() !== GNOSIS_USDC_ADDRESS.toLowerCase()) { - const [tokenInUsdcPool, usdcBzzPool] = await Promise.all([ - findPoolBetween(effectiveTokenIn, GNOSIS_USDC_ADDRESS), - findDirectBzzPool(GNOSIS_USDC_ADDRESS), - ]); - - if (tokenInUsdcPool && usdcBzzPool) { - const path = encodeTwoHopPath( - effectiveTokenIn, - tokenInUsdcPool.fee, - GNOSIS_USDC_ADDRESS, - usdcBzzPool.fee - ); - routes.push({ - path, - isNative: isNativeXdai, - fees: [tokenInUsdcPool.fee, usdcBzzPool.fee], - description: isNativeXdai - ? `xDAI → WXDAI → USDC → BZZ (${tokenInUsdcPool.fee / 10000}% + ${usdcBzzPool.fee / 10000}%)` - : `tokenIn → USDC → BZZ (${tokenInUsdcPool.fee / 10000}% + ${usdcBzzPool.fee / 10000}%)`, - }); - } - } - - if (effectiveTokenIn.toLowerCase() !== GNOSIS_WXDAI_ADDRESS.toLowerCase()) { - const [tokenInWxdaiPool, wxdaiBzzPool] = await Promise.all([ - findPoolBetween(effectiveTokenIn, GNOSIS_WXDAI_ADDRESS), - findDirectBzzPool(GNOSIS_WXDAI_ADDRESS), - ]); - - if (tokenInWxdaiPool && wxdaiBzzPool) { - const path = encodeTwoHopPath( - effectiveTokenIn, - tokenInWxdaiPool.fee, - GNOSIS_WXDAI_ADDRESS, - wxdaiBzzPool.fee - ); - routes.push({ - path, - isNative: isNativeXdai, - fees: [tokenInWxdaiPool.fee, wxdaiBzzPool.fee], - description: isNativeXdai - ? `xDAI → WXDAI (2-hop) → BZZ (${tokenInWxdaiPool.fee / 10000}% + ${wxdaiBzzPool.fee / 10000}%)` - : `tokenIn → WXDAI → BZZ (${tokenInWxdaiPool.fee / 10000}% + ${wxdaiBzzPool.fee / 10000}%)`, - }); - } - } - - return routes; -} - -/** - * Preferred route only (first in {@link findSushiRoutes} order). - */ -export async function findSushiRoute(fromToken: string): Promise { - const routes = await findSushiRoutes(fromToken); - return routes[0] ?? null; -} - -/** - * True if this Gnosis "from" token can fund stamps: BZZ (direct) or any token - * {@link findSushiRoute} can swap to BZZ via SushiSwap V3. - */ -export async function gnosisFromTokenCanReachBzz(fromToken: string): Promise { - const lower = fromToken.toLowerCase(); - if (lower === ZERO_ADDRESS || lower === '0x0') { - return (await findSushiRoute(fromToken)) !== null; - } - try { - if (getAddress(fromToken).toLowerCase() === getAddress(GNOSIS_BZZ_ADDRESS).toLowerCase()) { - return true; - } - } catch { - return false; - } - return (await findSushiRoute(fromToken)) !== null; -} - -// ─── Quote ──────────────────────────────────────────────────────────────────── - -/** - * Gets a quote for buying `bzzAmount` BZZ by swapping `fromToken` on Gnosis - * via the SushiSwapStampsRouter contract. Uses eth_call so no gas is consumed. - */ -export const getSushiQuote = async (params: SushiQuoteParams): Promise => { - const { - fromToken, - bzzAmount, - slippagePercent = DEFAULT_SLIPPAGE, - tokenSymbol = 'Token', - tokenDecimals = 18, - tokenPriceUsd = 0, - } = params; - - console.log('🍣 Getting SushiSwap quote for BZZ purchase…', { - fromToken, - bzzAmount, - slippagePercent, - }); - - const routes = await performWithRetry(() => findSushiRoutes(fromToken), 'findSushiRoutes'); - - if (routes.length === 0) { - throw new Error( - `No SushiSwap route found from ${tokenSymbol} to BZZ on Gnosis. ` + - 'Try using USDC or xDAI instead.' - ); - } - - const { client } = getGnosisPublicClient(); - - let amountInBeforeSlippage: bigint | undefined; - let route: SushiRouteInfo | undefined; - let lastQuoteError: unknown; - - for (const candidate of routes) { - const isSingleHop = candidate.fees.length === 1; - try { - if (isSingleHop) { - const effectiveTokenIn = candidate.isNative ? GNOSIS_WXDAI_ADDRESS : fromToken; - const result = await client.simulateContract({ - address: SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'quoteSingleHop', - args: [ - effectiveTokenIn as `0x${string}`, - candidate.fees[0], - BigInt(bzzAmount), - ], - }); - amountInBeforeSlippage = result.result as bigint; - } else { - const result = await client.simulateContract({ - address: SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'quoteMultiHop', - args: [candidate.path, BigInt(bzzAmount)], - }); - amountInBeforeSlippage = result.result as bigint; - } - route = candidate; - console.log('🍣 Route quoted:', route.description); - break; - } catch (e) { - lastQuoteError = e; - console.warn('🍣 Quote failed for route, trying next…', candidate.description, e); - } - } - - if (route === undefined || amountInBeforeSlippage === undefined) { - throw new Error( - `Could not get a SushiSwap quote from ${tokenSymbol} to BZZ (tried ${routes.length} on-chain route(s)). ` + - 'Try another token or a smaller capacity.' - ); - } - - // Apply slippage buffer. - const slippageBps = BigInt(Math.round(slippagePercent * 100)); // percent → bps - const maxAmountIn = - (amountInBeforeSlippage * (10000n + slippageBps)) / 10000n; - - // Compute approximate USD cost. - let totalAmountUSD = 0; - if (tokenPriceUsd > 0) { - const amountInFormatted = - Number(amountInBeforeSlippage) / 10 ** tokenDecimals; - totalAmountUSD = amountInFormatted * tokenPriceUsd; - } - - console.log('✅ SushiSwap quote:', { - route: route.description, - amountInBeforeSlippage: amountInBeforeSlippage.toString(), - maxAmountIn: maxAmountIn.toString(), - totalAmountUSD, - }); - - return { - maxAmountIn, - amountInBeforeSlippage, - totalAmountUSD, - route, - tokenIn: route.isNative ? ZERO_ADDRESS : fromToken, - tokenInSymbol: tokenSymbol, - tokenInDecimals: tokenDecimals, - }; -}; - -// ─── Allowance Check ────────────────────────────────────────────────────────── - -/** - * Checks whether the user has approved enough `tokenIn` to the router. - */ -export const checkRouterAllowance = async ( - userAddress: string, - tokenIn: string, - requiredAmount: bigint -): Promise => { - if (tokenIn === ZERO_ADDRESS || tokenIn === '0x0') { - return true; // Native xDAI doesn't need approval. - } - - try { - const { client } = getGnosisPublicClient(); - const allowance = await client.readContract({ - address: tokenIn as `0x${string}`, - abi: parseAbi([ - 'function allowance(address owner, address spender) external view returns (uint256)', - ]), - functionName: 'allowance', - args: [userAddress as `0x${string}`, SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`], - }); - - return BigInt(allowance.toString()) >= requiredAmount; - } catch (error) { - console.warn('⚠️ Could not check router allowance, will include approval:', error); - return false; - } -}; - -// ─── Execute ────────────────────────────────────────────────────────────────── - -/** - * Executes a SushiSwap token → BZZ → stamp purchase (create or top-up) in a - * single on-chain transaction via the SushiSwapStampsRouter contract. - */ -export const executeSushiSwap = async (params: SushiExecuteParams): Promise => { - const { - fromToken, - bzzAmount, - slippagePercent = DEFAULT_SLIPPAGE, - address, - swarmConfig, - topUpBatchId, - nodeAddress, - walletClient, - publicClient, - setStatusMessage, - onTransactionConfirmed, - } = params; - - console.log('🍣 Executing SushiSwap stamp purchase…'); - - // ── 1. Get / reuse quote ─────────────────────────────────────────────────── - setStatusMessage({ step: 'Quoting', message: 'Getting SushiSwap quote…' }); - - const quote = params.quote ?? (await getSushiQuote({ - fromToken, - bzzAmount, - slippagePercent, - tokenSymbol: params.tokenSymbol, - tokenDecimals: params.tokenDecimals, - tokenPriceUsd: params.tokenPriceUsd, - })); - - const { maxAmountIn, route } = quote; - const isNative = route.isNative; - const isTopUp = Boolean(topUpBatchId); - - // ── 2. Approve router (ERC20 only) ──────────────────────────────────────── - if (!isNative) { - const tokenIn = isNative ? GNOSIS_WXDAI_ADDRESS : fromToken; - const hasAllowance = await checkRouterAllowance(address, tokenIn, maxAmountIn); - - if (!hasAllowance) { - setStatusMessage({ step: 'Approval', message: 'Approving token for router…' }); - console.log('🔐 Approving router to spend token…', { tokenIn, maxAmountIn: maxAmountIn.toString() }); - - const MAX_UINT256 = - 115792089237316195423570985008687907853269984665640564039457584007913129639935n; - - const approveTxHash = await walletClient.writeContract({ - address: tokenIn as `0x${string}`, - abi: parseAbi(['function approve(address spender, uint256 amount) external returns (bool)']), - functionName: 'approve', - args: [SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, MAX_UINT256], - }); - - console.log('📝 Approval tx:', approveTxHash); - setStatusMessage({ step: 'Approval', message: 'Waiting for approval confirmation…' }); - - const approveReceipt = await publicClient.waitForTransactionReceipt({ - hash: approveTxHash, - timeout: TRANSACTION_TIMEOUT_MS, - pollingInterval: getPollingInterval(100), // Gnosis chainId = 100 - }); - - if (approveReceipt.status !== 'success') { - throw new Error('Token approval transaction failed'); - } - console.log('✅ Router approved'); - } else { - console.log('✅ Router already approved, skipping approval'); - } - } - - // ── 3. Build stamp registry params ──────────────────────────────────────── - const bzzAmountBigInt = BigInt(bzzAmount); - - setStatusMessage({ - step: 'Swapping', - message: isTopUp ? 'Topping up storage via SushiSwap…' : 'Buying storage via SushiSwap…', - }); - - // ── 4. Build and send the router transaction ─────────────────────────────── - let txHash: `0x${string}`; - - if (isTopUp && topUpBatchId) { - // Top-up branch - const topupAmountPerChunk = BigInt(swarmConfig.swarmBatchInitialBalance); - - if (isNative) { - txHash = await walletClient.writeContract({ - address: SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'topUpNative', - args: [route.path, maxAmountIn, bzzAmountBigInt, topUpBatchId as `0x${string}`, topupAmountPerChunk], - value: maxAmountIn, - }); - } else { - txHash = await walletClient.writeContract({ - address: SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'topUp', - args: [ - route.path, - maxAmountIn, - bzzAmountBigInt, - topUpBatchId as `0x${string}`, - topupAmountPerChunk, - ], - }); - } - } else { - // Create-batch branch - const batchParams = { - owner: address as `0x${string}`, - nodeAddress: nodeAddress as `0x${string}`, - initialBalancePerChunk: BigInt(swarmConfig.swarmBatchInitialBalance), - depth: Number(swarmConfig.swarmBatchDepth), - bucketDepth: Number(swarmConfig.swarmBatchBucketDepth), - nonce: swarmConfig.swarmBatchNonce as `0x${string}`, - immutable_: Boolean(swarmConfig.swarmBatchImmutable), - }; - - if (isNative) { - txHash = await walletClient.writeContract({ - address: SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'createBatchNative', - args: [route.path, maxAmountIn, bzzAmountBigInt, batchParams], - value: maxAmountIn, - }); - } else { - txHash = await walletClient.writeContract({ - address: SUSHI_STAMPS_ROUTER_ADDRESS as `0x${string}`, - abi: SUSHI_STAMPS_ROUTER_ABI, - functionName: 'createBatch', - args: [route.path, maxAmountIn, bzzAmountBigInt, batchParams], - }); - } - } - - console.log('📝 SushiSwap router tx:', txHash); - - setStatusMessage({ - step: 'Confirming', - message: 'Waiting for transaction confirmation…', - }); - - // ── 5. Wait for confirmation ─────────────────────────────────────────────── - const receipt = await publicClient.waitForTransactionReceipt({ - hash: txHash, - timeout: TRANSACTION_TIMEOUT_MS, - pollingInterval: getPollingInterval(100), // Gnosis chainId = 100 - }); - - if (receipt.status !== 'success') { - throw new Error('SushiSwap transaction failed on-chain'); - } - - console.log('✅ SushiSwap stamp transaction confirmed:', txHash); - - if (onTransactionConfirmed) { - onTransactionConfirmed(); - } -}; diff --git a/src/app/components/SwapComponent.tsx b/src/app/components/SwapComponent.tsx index f1cb2c8..a1c7206 100644 --- a/src/app/components/SwapComponent.tsx +++ b/src/app/components/SwapComponent.tsx @@ -22,7 +22,6 @@ import { GNOSIS_DESTINATION_TOKEN, TIME_OPTIONS, GNOSIS_CUSTOM_REGISTRY_ADDRESS, - SUSHI_STAMPS_ROUTER_ADDRESS, DEFAULT_BEE_API_URL, DEFAULT_SLIPPAGE, MIN_TOKEN_BALANCE_USD, @@ -63,12 +62,9 @@ import { useTimer } from './TimerUtils'; // Note: LiFi quote functions removed - now using Relay API via RelayQuotes.ts import { getRelaySwapQuotes, - getRelayCrossChainWithSushiQuote, executeRelaySteps, - RelayQuoteResponse, parseRelayError, } from './RelayQuotes'; -import { getSushiQuote, executeSushiSwap, SushiQuoteResult } from './SushiQuotes'; import { handleFileUpload as uploadFile, handleMultiFileUpload, @@ -381,80 +377,23 @@ const SwapComponent: React.FC = () => { fromToken, }); - // ── Gnosis + non-BZZ token: use SushiSwapStampsRouter for quote ────────── - const isGnosisNonBzz = - selectedChainId === ChainId.DAI && - fromToken && - getAddress(fromToken) !== getAddress(GNOSIS_BZZ_ADDRESS) && - SUSHI_STAMPS_ROUTER_ADDRESS !== ''; - - // ── Cross-chain + router deployed: Relay → USDC → Sushi → BZZ → stamp ── - const isCrossChainWithSushi = - selectedChainId !== ChainId.DAI && SUSHI_STAMPS_ROUTER_ADDRESS !== ''; - - let totalAmountUSD: number; - - if (isGnosisNonBzz) { - console.log('🍣 Using SushiSwap quote for Gnosis token…'); - - const tokenPriceUsd = selectedTokenInfo ? Number(selectedTokenInfo.priceUSD) : 0; - const tokenDecimals = selectedTokenInfo?.decimals ?? 18; - const tokenSymbol = selectedTokenInfo?.symbol ?? 'Token'; - - const sushiQuote = await getSushiQuote({ - fromToken, - bzzAmount, - slippagePercent: useCustomSlippage ? customSlippagePercent : DEFAULT_SLIPPAGE, - tokenSymbol, - tokenDecimals, - tokenPriceUsd, - }); - - if (abortSignal.aborted) return; - - totalAmountUSD = sushiQuote.totalAmountUSD; - console.log(`💰 SushiSwap quote: $${totalAmountUSD.toFixed(2)}`); - } else if (isCrossChainWithSushi) { - // ── Cross-chain: Relay bridges to USDC, SushiRouter swaps → BZZ → stamp - console.log('🌉 Using Relay→USDC→Sushi quote for cross-chain…'); - - const crossChainResult = await getRelayCrossChainWithSushiQuote({ - selectedChainId, - fromToken, - address, - bzzAmount, - nodeAddress, - swarmConfig, - topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, - setEstimatedTime: () => {}, - isForEstimation: true, - slippagePercent: useCustomSlippage ? customSlippagePercent : undefined, - }); - - if (abortSignal.aborted) return; - - totalAmountUSD = crossChainResult.totalAmountUSD; - console.log(`💰 Cross-chain USDC+Sushi estimate: $${totalAmountUSD.toFixed(2)}`); - } else { - // ── Gnosis + BZZ direct (or fallback): use Relay ─────────────────────── - const relayQuoteResult = await getRelaySwapQuotes({ - selectedChainId, - fromToken, - address, - bzzAmount, - nodeAddress, - swarmConfig, - topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, - setEstimatedTime: () => {}, - isForEstimation: true, - slippagePercent: useCustomSlippage ? customSlippagePercent : undefined, - }); + const relayQuoteResult = await getRelaySwapQuotes({ + selectedChainId, + fromToken, + address, + bzzAmount, + nodeAddress, + swarmConfig, + topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, + setEstimatedTime: () => {}, + isForEstimation: true, + slippagePercent: useCustomSlippage ? customSlippagePercent : undefined, + }); - if (abortSignal.aborted) return; + if (abortSignal.aborted) return; - totalAmountUSD = relayQuoteResult.totalAmountUSD; - console.log(`💰 Relay price estimation complete: $${totalAmountUSD.toFixed(2)}`); - } + const totalAmountUSD = relayQuoteResult.totalAmountUSD; + console.log(`💰 Relay price estimation complete: $${totalAmountUSD.toFixed(2)}`); // If operation was aborted, don't continue if (abortSignal.aborted) { @@ -889,150 +828,6 @@ const SwapComponent: React.FC = () => { })); }; - const handleDirectBzzTransactions = async (updatedConfig: any) => { - // Ensure we have all needed objects and data - if (!address || !publicClient || !walletClient) { - console.error('Missing required objects for direct BZZ transaction'); - return; - } - - try { - // Calculate amount based on whether this is a top-up or new batch - let totalAmount: bigint; - - if (isTopUp && originalStampInfo) { - // For top-ups, use the original depth from the stamp - totalAmount = calculateTopUpAmount(originalStampInfo.depth); - - // Update swarmBatchInitialBalance for top-up (price per chunk) - if (currentPrice !== null && selectedDays) { - const initialPaymentPerChunkPerDay = BigInt(currentPrice) * BigInt(17280); - const pricePerChunkForDuration = initialPaymentPerChunkPerDay * BigInt(selectedDays); - setSwarmConfig(prev => ({ - ...prev, - swarmBatchInitialBalance: pricePerChunkForDuration.toString(), - })); - } - } else { - // For new batches, use the total from updatedConfig - totalAmount = BigInt(updatedConfig.swarmBatchTotal); - } - - // Generate specific transaction message based on operation type - const operationMsg = isTopUp - ? `Topping up batch ${ - topUpBatchId?.startsWith('0x') ? topUpBatchId.slice(2, 8) : topUpBatchId?.slice(0, 6) - }...${topUpBatchId?.slice(-4)}` - : 'Buying storage...'; - - // Approval is now handled separately, proceed directly to stamp creation - - // Prepare contract write parameters - different based on operation type - let contractWriteParams; - - if (isTopUp && topUpBatchId) { - // Top up existing batch - contractWriteParams = { - address: GNOSIS_CUSTOM_REGISTRY_ADDRESS as `0x${string}`, - abi: parseAbi(updatedConfig.swarmContractAbi), - functionName: 'topUpBatch', - args: [topUpBatchId as `0x${string}`, updatedConfig.swarmBatchInitialBalance], - account: address, - }; - } else { - // Create new batch - contractWriteParams = { - address: GNOSIS_CUSTOM_REGISTRY_ADDRESS as `0x${string}`, - abi: parseAbi(updatedConfig.swarmContractAbi), - functionName: 'createBatchRegistry', - args: [ - address, - nodeAddress, - updatedConfig.swarmBatchInitialBalance, - updatedConfig.swarmBatchDepth, - updatedConfig.swarmBatchBucketDepth, - updatedConfig.swarmBatchNonce, - updatedConfig.swarmBatchImmutable, - ], - account: address, - }; - } - - console.log('Creating transaction with params:', contractWriteParams); - - // Execute the batch creation or top-up - const batchTxHash = await walletClient.writeContract(contractWriteParams); - console.log(`${isTopUp ? 'Top up' : 'Create batch'} transaction hash:`, batchTxHash); - - // Wait for batch transaction to be mined - const batchReceipt = await publicClient.waitForTransactionReceipt({ - hash: batchTxHash, - pollingInterval: getPollingInterval(chainId), - }); - - if (batchReceipt.status === 'success') { - if (isTopUp) { - // For top-up, we already have the batch ID - console.log('Successfully topped up batch ID:', topUpBatchId); - setPostageBatchId(topUpBatchId as string); - - // Set top-up completion info - setTopUpCompleted(true); - setTopUpInfo({ - batchId: topUpBatchId as string, - days: selectedDays || 0, - cost: totalUsdAmount || '0', - }); - - setStatusMessage({ - step: 'Complete', - message: 'Batch Topped Up Successfully', - isSuccess: true, - }); - - // Update upload history with new expiry date immediately - if (address && topUpBatchId && selectedDays) { - updateHistoryAfterTopUp(topUpBatchId as string, selectedDays, address); - } - // Don't set upload step for top-ups - } else { - try { - // Calculate the batch ID for logging - const calculatedBatchId = readBatchId( - updatedConfig.swarmBatchNonce, - GNOSIS_CUSTOM_REGISTRY_ADDRESS - ); - - console.log('Batch created successfully with ID:', calculatedBatchId); - - setStatusMessage({ - step: 'Complete', - message: 'Storage Bought Successfully', - isSuccess: true, - warning: - 'Note: It takes approximately 1-2 minutes for new storage to become accessible on the network. Please wait before uploading.', - }); - setIsNewStampCreated(true); - setUploadStep('ready'); - } catch (error) { - console.error('Failed to process batch completion:', error); - throw new Error('Failed to process batch completion'); - } - } - } else { - throw new Error(`${isTopUp ? 'Top-up' : 'Batch creation'} failed`); - } - } catch (error) { - console.error(`Error in direct BZZ transactions: ${error}`); - setStatusMessage({ - step: 'Error', - message: 'Transaction failed', - error: error instanceof Error ? error.message : 'Unknown error occurred', - isError: true, - }); - } - }; - // Note: Old LiFi functions removed (handleGnosisTokenSwap, handleCrossChainSwap, // handleChainSwitch, handleGnosisRoute) - now using Relay API via RelayQuotes.ts @@ -1122,240 +917,99 @@ const SwapComponent: React.FC = () => { } setStatusMessage({ - step: 'Calculation', - message: 'Calculating amounts...', + step: 'Quoting', + message: 'Getting quote...', }); - // ── Branch 1: Gnosis + BZZ direct → no swap needed ───────────────────── - if ( - selectedChainId !== null && - selectedChainId === ChainId.DAI && - getAddress(fromToken) === getAddress(GNOSIS_BZZ_ADDRESS) - ) { - await handleDirectBzzTransactions(updatedConfig); - } else if ( - // ── Branch 2: Gnosis + other token → SushiSwapStampsRouter ──────────── - selectedChainId !== null && - selectedChainId === ChainId.DAI && - SUSHI_STAMPS_ROUTER_ADDRESS !== '' - ) { - const tokenPriceUsd = selectedToken ? Number(selectedTokenInfo?.priceUSD ?? 0) : 0; - const tokenDecimals = selectedTokenInfo?.decimals ?? 18; - const tokenSymbol = selectedTokenInfo?.symbol ?? 'Token'; - - await executeSushiSwap({ - fromToken, - bzzAmount: updatedConfig.swarmBatchTotal, - slippagePercent: useCustomSlippage ? customSlippagePercent : DEFAULT_SLIPPAGE, - address, - swarmConfig: updatedConfig, - topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, - nodeAddress, - walletClient, - publicClient, - tokenSymbol, - tokenDecimals, - tokenPriceUsd, - setStatusMessage, - onTransactionConfirmed: () => { - console.log('🍣 SushiSwap stamp transaction confirmed!'); - }, - }); - - console.log('🎉 SushiSwap stamp purchase completed successfully!'); - - // Reset timer when done - resetTimer(); - - // Handle post-swap completion flow (same as original LiFi implementation) - try { - if (isTopUp && topUpBatchId) { - console.log('Successfully topped up batch ID:', topUpBatchId); - setPostageBatchId(topUpBatchId); - - // Set top-up completion info - setTopUpCompleted(true); - setTopUpInfo({ - batchId: topUpBatchId, - days: selectedDays || 0, - cost: totalUsdAmount || '0', - }); - - setStatusMessage({ - step: 'Complete', - message: 'Batch Topped Up Successfully', - isSuccess: true, - }); - - // Update upload history with new expiry date immediately - if (address && selectedDays) { - updateHistoryAfterTopUp(topUpBatchId, selectedDays, address); - } - } else { - // Calculate the batch ID for new batch creation - const calculatedBatchId = readBatchId( - updatedConfig.swarmBatchNonce, - GNOSIS_CUSTOM_REGISTRY_ADDRESS - ); + const relayQuoteResult = await getRelaySwapQuotes({ + selectedChainId, + fromToken, + address, + bzzAmount: updatedConfig.swarmBatchTotal, + nodeAddress, + swarmConfig: updatedConfig, + topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, + setEstimatedTime: () => {}, + isForEstimation: false, + slippagePercent: useCustomSlippage ? customSlippagePercent : undefined, + }); - console.log('Batch created successfully with ID:', calculatedBatchId); - setPostageBatchId(calculatedBatchId); + console.log('✅ Relay execution quotes ready:', { + totalUSD: `$${relayQuoteResult.totalAmountUSD.toFixed(2)}`, + steps: relayQuoteResult.steps.length, + estimatedTime: relayQuoteResult.estimatedTime, + }); - setStatusMessage({ - step: 'Complete', - message: 'Storage Bought Successfully', - isSuccess: true, - warning: - 'Note: It takes approximately 1-2 minutes for new storage to become accessible on the network. Please wait before uploading.', - }); + setStatusMessage({ + step: 'Preparing', + message: 'Preparing swap...', + }); - // Transition to upload step - this was missing! - setIsNewStampCreated(true); - setUploadStep('ready'); - } - } catch (error) { - console.error('Failed to process batch completion:', error); + await executeRelaySteps( + relayQuoteResult.relayQuoteResponse, + walletClient, + publicClient, + setStatusMessage, + () => { + console.log( + '🚀 Transaction confirmed! Starting timer:', + relayQuoteResult.estimatedTime, + 'seconds' + ); + setEstimatedTime(relayQuoteResult.estimatedTime); setStatusMessage({ - step: 'Error', - message: 'Failed to process batch completion', - error: error instanceof Error ? error.message : 'Unknown error', - isError: true, + step: 'Relay', + message: 'Executing swap...', }); } - } else { - // ── Branch 3: cross-chain ─────────────────────────────────────────────── - // Prefer Relay → USDC → SushiRouter → BZZ → stamp (better routing). - // Fall back to legacy Relay → BZZ path if router is not deployed. - const useSushiBridge = SUSHI_STAMPS_ROUTER_ADDRESS !== ''; + ); - setStatusMessage({ - step: 'Quoting', - message: 'Getting quote...', - }); + console.log('🎉 Relay swap completed successfully!'); + resetTimer(); - let crossChainRelayResponse: RelayQuoteResponse; - let crossChainEstimatedTime: number; - - if (useSushiBridge) { - console.log('🌉 Cross-chain via Relay→USDC→SushiRouter→BZZ→stamp…'); - - const result = await getRelayCrossChainWithSushiQuote({ - selectedChainId, - fromToken, - address, - bzzAmount: updatedConfig.swarmBatchTotal, - nodeAddress, - swarmConfig: updatedConfig, - topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, - setEstimatedTime: () => {}, - isForEstimation: false, - slippagePercent: useCustomSlippage ? customSlippagePercent : undefined, + try { + if (isTopUp && topUpBatchId) { + console.log('Successfully topped up batch ID:', topUpBatchId); + setPostageBatchId(topUpBatchId); + setTopUpCompleted(true); + setTopUpInfo({ + batchId: topUpBatchId, + days: selectedDays || 0, + cost: totalUsdAmount || '0', }); - - crossChainRelayResponse = result.relayQuoteResponse; - crossChainEstimatedTime = result.estimatedTime; - - console.log('✅ Cross-chain USDC+Sushi quotes ready:', { - totalUSD: `$${result.totalAmountUSD.toFixed(2)}`, - steps: result.steps.length, - estimatedTime: result.estimatedTime, + setStatusMessage({ + step: 'Complete', + message: 'Batch Topped Up Successfully', + isSuccess: true, }); + if (address && selectedDays) { + updateHistoryAfterTopUp(topUpBatchId, selectedDays, address); + } } else { - // Legacy: Relay bridges directly to BZZ - const relayQuoteResult = await getRelaySwapQuotes({ - selectedChainId, - fromToken, - address, - bzzAmount: updatedConfig.swarmBatchTotal, - nodeAddress, - swarmConfig: updatedConfig, - topUpBatchId: isTopUp ? topUpBatchId || undefined : undefined, - setEstimatedTime: () => {}, - isForEstimation: false, - slippagePercent: useCustomSlippage ? customSlippagePercent : undefined, - }); - - crossChainRelayResponse = relayQuoteResult.relayQuoteResponse; - crossChainEstimatedTime = relayQuoteResult.estimatedTime; - - console.log('✅ Relay execution quotes ready:', { - totalUSD: `$${relayQuoteResult.totalAmountUSD.toFixed(2)}`, - steps: relayQuoteResult.steps.length, - estimatedTime: relayQuoteResult.estimatedTime, + const calculatedBatchId = readBatchId( + updatedConfig.swarmBatchNonce, + GNOSIS_CUSTOM_REGISTRY_ADDRESS + ); + console.log('Batch created successfully with ID:', calculatedBatchId); + setPostageBatchId(calculatedBatchId); + setStatusMessage({ + step: 'Complete', + message: 'Storage Bought Successfully', + isSuccess: true, + warning: + 'Note: It takes approximately 1-2 minutes for new storage to become accessible on the network. Please wait before uploading.', }); + setIsNewStampCreated(true); + setUploadStep('ready'); } - + } catch (error) { + console.error('Failed to process Relay batch completion:', error); setStatusMessage({ - step: 'Preparing', - message: 'Preparing cross-chain swap...', + step: 'Error', + message: 'Failed to process batch completion', + error: error instanceof Error ? error.message : 'Unknown error', + isError: true, }); - - await executeRelaySteps( - crossChainRelayResponse, - walletClient, - publicClient, - setStatusMessage, - () => { - console.log( - '🚀 Transaction confirmed! Starting timer:', - crossChainEstimatedTime, - 'seconds' - ); - setEstimatedTime(crossChainEstimatedTime); - setStatusMessage({ - step: 'Relay', - message: 'Executing cross-chain swap...', - }); - } - ); - - console.log('🎉 Relay swap completed successfully!'); - resetTimer(); - - try { - if (isTopUp && topUpBatchId) { - console.log('Successfully topped up batch ID:', topUpBatchId); - setPostageBatchId(topUpBatchId); - setTopUpCompleted(true); - setTopUpInfo({ - batchId: topUpBatchId, - days: selectedDays || 0, - cost: totalUsdAmount || '0', - }); - setStatusMessage({ - step: 'Complete', - message: 'Batch Topped Up Successfully', - isSuccess: true, - }); - if (address && selectedDays) { - updateHistoryAfterTopUp(topUpBatchId, selectedDays, address); - } - } else { - const calculatedBatchId = readBatchId( - updatedConfig.swarmBatchNonce, - GNOSIS_CUSTOM_REGISTRY_ADDRESS - ); - console.log('Batch created successfully with ID:', calculatedBatchId); - setPostageBatchId(calculatedBatchId); - setStatusMessage({ - step: 'Complete', - message: 'Storage Bought Successfully', - isSuccess: true, - warning: - 'Note: It takes approximately 1-2 minutes for new storage to become accessible on the network. Please wait before uploading.', - }); - setIsNewStampCreated(true); - setUploadStep('ready'); - } - } catch (error) { - console.error('Failed to process Relay batch completion:', error); - setStatusMessage({ - step: 'Error', - message: 'Failed to process batch completion', - error: error instanceof Error ? error.message : 'Unknown error', - isError: true, - }); - } } } catch (error) { console.error('An error occurred:', error); diff --git a/src/app/components/TokenUtils.ts b/src/app/components/TokenUtils.ts index 14fc041..3f6e9a9 100644 --- a/src/app/components/TokenUtils.ts +++ b/src/app/components/TokenUtils.ts @@ -7,29 +7,8 @@ import { } from '@lifi/sdk'; import { useState, useCallback } from 'react'; import { formatUnits } from 'viem'; -import { gnosisFromTokenCanReachBzz } from './SushiQuotes'; import { performWithRetry, toChecksumAddress } from './utils'; -/** Parallel RPC checks for Gnosis route gating (each token runs multiple reads). */ -const GNOSIS_ROUTE_CHECK_CONCURRENCY = 4; - -async function filterGnosisBalancesToSushiRoutable( - tokensWithPositiveBalance: T[] -): Promise { - if (tokensWithPositiveBalance.length === 0) { - return []; - } - const kept: T[] = []; - for (let i = 0; i < tokensWithPositiveBalance.length; i += GNOSIS_ROUTE_CHECK_CONCURRENCY) { - const chunk = tokensWithPositiveBalance.slice(i, i + GNOSIS_ROUTE_CHECK_CONCURRENCY); - const flags = await Promise.all( - chunk.map(async t => ((await gnosisFromTokenCanReachBzz(t.address)) ? t : null)) - ); - kept.push(...(flags.filter(Boolean) as T[])); - } - return kept; -} - // List of popular tokens to prioritize when wallet is not connected const POPULAR_TOKENS = [ 'ETH', @@ -146,28 +125,11 @@ export const useTokenManagement = ( ); console.log('Token balances:', balances); - let effectiveBalances = balances; - if (currentChainId === ChainId.DAI && balances?.[currentChainId]) { - const chainList = balances[currentChainId]; - const positive = chainList.filter(t => (t?.amount ?? 0n) > 0n); - if (positive.length > 0) { - const routable = await filterGnosisBalancesToSushiRoutable(positive); - const allow = new Set(routable.map(t => t.address.toLowerCase())); - const filteredChain = chainList.filter( - t => (t?.amount ?? 0n) === 0n || allow.has(t.address.toLowerCase()) - ); - effectiveBalances = { ...balances, [currentChainId]: filteredChain }; - console.log( - `🍣 Gnosis: ${positive.length} token(s) with balance → ${routable.length} with Sushi route to BZZ` - ); - } - } - - setTokenBalances(effectiveBalances); + setTokenBalances(balances); // Find tokens with balance - if (effectiveBalances?.[currentChainId]) { - const tokensWithBalance = effectiveBalances[currentChainId] + if (balances?.[currentChainId]) { + const tokensWithBalance = balances[currentChainId] .filter(t => (t?.amount ?? 0n) > 0n) .sort((a, b) => { const aUsdValue = diff --git a/src/app/components/constants.ts b/src/app/components/constants.ts index 415623a..b7db665 100644 --- a/src/app/components/constants.ts +++ b/src/app/components/constants.ts @@ -260,176 +260,10 @@ export const V3_POOL_ABI = [ export const BZZ_USDC_POOL_ADDRESS = process.env.NEXT_PUBLIC_BZZ_USDC_POOL_ADDRESS || '0x6f30b7cf40cb423c1d23478a9855701ecf43931e'; -// USDC token on Gnosis (bridged) +// USDC token on Gnosis (bridged) – used by PriceTracker BZZ/USDC pool export const GNOSIS_USDC_ADDRESS = process.env.NEXT_PUBLIC_GNOSIS_USDC_ADDRESS || '0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83'; -/** - * Intermediate token Relay bridges to on Gnosis for cross-chain stamp purchases. - * Relay has excellent routes to this token on most chains; the SushiSwapStampsRouter - * then swaps it → BZZ and creates the stamp atomically on Gnosis. - * - * IMPORTANT: This is Circle's native USDC on Gnosis (0x2a22…), NOT the older Ethereum- - * bridged USDC (0xDDAf…). Relay only supports routing to the native address. - * The SushiSwapStampsRouter handles the two-hop: native USDC → bridged USDC → BZZ, - * using the fee-100 Sushi V3 pool between the two USDC tokens. - * - * Override with NEXT_PUBLIC_RELAY_BRIDGE_TOKEN_ON_GNOSIS when using a different token - * (must have a working Sushi V3 route to BZZ on Gnosis). - */ -export const RELAY_BRIDGE_TOKEN_ON_GNOSIS = - process.env.NEXT_PUBLIC_RELAY_BRIDGE_TOKEN_ON_GNOSIS || - '0x2a22f9c3b484c3629090feed35f17ff8f88f76f0'; // native Circle USDC on Gnosis - -/** Decimals of {@link RELAY_BRIDGE_TOKEN_ON_GNOSIS}. Override when changing the bridge token. */ -export const RELAY_BRIDGE_TOKEN_DECIMALS = Number( - process.env.NEXT_PUBLIC_RELAY_BRIDGE_TOKEN_DECIMALS ?? '6' -); - -/** Symbol of {@link RELAY_BRIDGE_TOKEN_ON_GNOSIS} (used for display/logging). */ -export const RELAY_BRIDGE_TOKEN_SYMBOL = - process.env.NEXT_PUBLIC_RELAY_BRIDGE_TOKEN_SYMBOL || 'USDC'; - -// ─── SushiSwap V3 on Gnosis ──────────────────────────────────────────────── - -/** SushiSwap V3 Factory on Gnosis – used for pool discovery */ -export const SUSHI_FACTORY_ADDRESS = - process.env.NEXT_PUBLIC_SUSHI_FACTORY_ADDRESS || '0xf78031cbca409f2fb6876bdfdbc1b2df24cf9bef'; - -/** SushiSwap V3 QuoterV2 on Gnosis – used for exact-output price estimation */ -export const SUSHI_QUOTER_ADDRESS = - process.env.NEXT_PUBLIC_SUSHI_QUOTER_ADDRESS || '0xb1e835dc2785b52265711e17fccb0fd018226a6e'; - -/** - * SushiSwapStampsRouter – our deployed router that swaps any Gnosis token → BZZ - * and atomically creates / tops up a Swarm stamp in a single transaction. - * Override with NEXT_PUBLIC_SUSHI_STAMPS_ROUTER_ADDRESS when using another deployment. - */ -export const SUSHI_STAMPS_ROUTER_ADDRESS = - process.env.NEXT_PUBLIC_SUSHI_STAMPS_ROUTER_ADDRESS || - '0xf244cC25EAD03a99de8B407A3237aaf54D1b779C'; - -/** Minimal ABI for the SushiSwap V3 Factory – only what we need for pool discovery */ -export const SUSHI_FACTORY_ABI = [ - { - inputs: [ - { internalType: 'address', name: 'tokenA', type: 'address' }, - { internalType: 'address', name: 'tokenB', type: 'address' }, - { internalType: 'uint24', name: 'fee', type: 'uint24' }, - ], - name: 'getPool', - outputs: [{ internalType: 'address', name: 'pool', type: 'address' }], - stateMutability: 'view', - type: 'function', - }, -] as const; - -/** Full ABI for the SushiSwapStampsRouter contract */ -export const SUSHI_STAMPS_ROUTER_ABI = [ - // ── Quote functions (call via eth_call / simulateContract) ───────────────── - { - inputs: [ - { internalType: 'address', name: 'tokenIn', type: 'address' }, - { internalType: 'uint24', name: 'fee', type: 'uint24' }, - { internalType: 'uint256', name: 'bzzAmountOut', type: 'uint256' }, - ], - name: 'quoteSingleHop', - outputs: [{ internalType: 'uint256', name: 'amountIn', type: 'uint256' }], - stateMutability: 'nonpayable', - type: 'function', - }, - { - inputs: [ - { internalType: 'bytes', name: 'path', type: 'bytes' }, - { internalType: 'uint256', name: 'bzzAmountOut', type: 'uint256' }, - ], - name: 'quoteMultiHop', - outputs: [{ internalType: 'uint256', name: 'amountIn', type: 'uint256' }], - stateMutability: 'nonpayable', - type: 'function', - }, - // ── Create batch (ERC20 input) ───────────────────────────────────────────── - { - inputs: [ - { internalType: 'bytes', name: 'path', type: 'bytes' }, - { internalType: 'uint256', name: 'maxAmountIn', type: 'uint256' }, - { internalType: 'uint256', name: 'bzzAmountOut', type: 'uint256' }, - { - components: [ - { internalType: 'address', name: 'owner', type: 'address' }, - { internalType: 'address', name: 'nodeAddress', type: 'address' }, - { internalType: 'uint256', name: 'initialBalancePerChunk', type: 'uint256' }, - { internalType: 'uint8', name: 'depth', type: 'uint8' }, - { internalType: 'uint8', name: 'bucketDepth', type: 'uint8' }, - { internalType: 'bytes32', name: 'nonce', type: 'bytes32' }, - { internalType: 'bool', name: 'immutable_', type: 'bool' }, - ], - internalType: 'struct SushiSwapStampsRouter.CreateBatchParams', - name: 'p', - type: 'tuple', - }, - ], - name: 'createBatch', - outputs: [], - stateMutability: 'nonpayable', - type: 'function', - }, - // ── Create batch (native xDAI input) ────────────────────────────────────── - { - inputs: [ - { internalType: 'bytes', name: 'path', type: 'bytes' }, - { internalType: 'uint256', name: 'maxAmountIn', type: 'uint256' }, - { internalType: 'uint256', name: 'bzzAmountOut', type: 'uint256' }, - { - components: [ - { internalType: 'address', name: 'owner', type: 'address' }, - { internalType: 'address', name: 'nodeAddress', type: 'address' }, - { internalType: 'uint256', name: 'initialBalancePerChunk', type: 'uint256' }, - { internalType: 'uint8', name: 'depth', type: 'uint8' }, - { internalType: 'uint8', name: 'bucketDepth', type: 'uint8' }, - { internalType: 'bytes32', name: 'nonce', type: 'bytes32' }, - { internalType: 'bool', name: 'immutable_', type: 'bool' }, - ], - internalType: 'struct SushiSwapStampsRouter.CreateBatchParams', - name: 'p', - type: 'tuple', - }, - ], - name: 'createBatchNative', - outputs: [], - stateMutability: 'payable', - type: 'function', - }, - // ── Top up (ERC20 input) ─────────────────────────────────────────────────── - { - inputs: [ - { internalType: 'bytes', name: 'path', type: 'bytes' }, - { internalType: 'uint256', name: 'maxAmountIn', type: 'uint256' }, - { internalType: 'uint256', name: 'bzzAmountOut', type: 'uint256' }, - { internalType: 'bytes32', name: 'batchId', type: 'bytes32' }, - { internalType: 'uint256', name: 'topupAmountPerChunk', type: 'uint256' }, - ], - name: 'topUp', - outputs: [], - stateMutability: 'nonpayable', - type: 'function', - }, - // ── Top up (native xDAI input) ───────────────────────────────────────────── - { - inputs: [ - { internalType: 'bytes', name: 'path', type: 'bytes' }, - { internalType: 'uint256', name: 'maxAmountIn', type: 'uint256' }, - { internalType: 'uint256', name: 'bzzAmountOut', type: 'uint256' }, - { internalType: 'bytes32', name: 'batchId', type: 'bytes32' }, - { internalType: 'uint256', name: 'topupAmountPerChunk', type: 'uint256' }, - ], - name: 'topUpNative', - outputs: [], - stateMutability: 'payable', - type: 'function', - }, -] as const; - /** * Note on naming convention: The terms "Batch" and "Stamps" are used interchangeably throughout the codebase. * "Batch" refers to a collection of stamps created in a single transaction and is the terminology used in the From e35c5afa55dee2924075e69b25988125cc317700 Mon Sep 17 00:00:00 2001 From: Cardinal Date: Fri, 26 Jun 2026 13:37:00 +0200 Subject: [PATCH 2/3] Remove now-unused Gnosis token constants GNOSIS_WXDAI_ADDRESS and GNOSIS_USDC_ADDRESS were only referenced by the deleted Sushi router flow; drop them now that purchases route through Relay. --- src/app/components/constants.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/app/components/constants.ts b/src/app/components/constants.ts index b7db665..d38b9f2 100644 --- a/src/app/components/constants.ts +++ b/src/app/components/constants.ts @@ -48,9 +48,6 @@ export const GNOSIS_PRICE_ORACLE_ADDRESS = export const GNOSIS_DESTINATION_TOKEN = process.env.NEXT_PUBLIC_GNOSIS_DESTINATION_TOKEN || '0x0000000000000000000000000000000000000000'; -export const GNOSIS_WXDAI_ADDRESS = - process.env.NEXT_PUBLIC_GNOSIS_WXDAI_ADDRESS || '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'; - // Static configuration export const MIN_TOKEN_BALANCE_USD = 0.5; @@ -256,14 +253,10 @@ export const V3_POOL_ABI = [ }, ] as const; -// Sushiswap V3 Pool address for BZZ/USDC on Gnosis (also used for price display) +// Sushiswap V3 Pool address for BZZ/USDC on Gnosis (read-only, used for price display) export const BZZ_USDC_POOL_ADDRESS = process.env.NEXT_PUBLIC_BZZ_USDC_POOL_ADDRESS || '0x6f30b7cf40cb423c1d23478a9855701ecf43931e'; -// USDC token on Gnosis (bridged) – used by PriceTracker BZZ/USDC pool -export const GNOSIS_USDC_ADDRESS = - process.env.NEXT_PUBLIC_GNOSIS_USDC_ADDRESS || '0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83'; - /** * Note on naming convention: The terms "Batch" and "Stamps" are used interchangeably throughout the codebase. * "Batch" refers to a collection of stamps created in a single transaction and is the terminology used in the From f7d30a951c50b7a84ee4dc7246ded4882c4f1ae5 Mon Sep 17 00:00:00 2001 From: Cardinal Date: Fri, 26 Jun 2026 13:42:25 +0200 Subject: [PATCH 3/3] Remove manual BZZ approval flow Relay inserts the BZZ approval as a swap step, so the separate same-chain approval button, dropdown, and allowance checks are redundant. Drop them and the now-unused helpers/imports so every purchase runs through one Relay flow. --- src/app/components/SwapComponent.tsx | 259 +-------------------------- 1 file changed, 4 insertions(+), 255 deletions(-) diff --git a/src/app/components/SwapComponent.tsx b/src/app/components/SwapComponent.tsx index a1c7206..af462df 100644 --- a/src/app/components/SwapComponent.tsx +++ b/src/app/components/SwapComponent.tsx @@ -4,18 +4,16 @@ import React, { useState, useEffect, useRef, useCallback } from 'react'; import { useAccount, useChainId, usePublicClient, useWalletClient, useSwitchChain } from 'wagmi'; import { watchChainId, getWalletClient } from '@wagmi/core'; import { useConnectModal } from '@rainbow-me/rainbowkit'; -import { config, getPollingInterval } from '@/app/wagmi'; +import { config } from '@/app/wagmi'; import { createConfig, EVM, ChainId, ChainType, getChains, Chain } from '@lifi/sdk'; import styles from './css/SwapComponent.module.css'; -import { parseAbi, formatUnits } from 'viem'; -import { getAddress } from 'viem'; +import { formatUnits } from 'viem'; import { ExecutionStatus, UploadStep } from './types'; import { GNOSIS_PRICE_ORACLE_ADDRESS, GNOSIS_PRICE_ORACLE_ABI, DEFAULT_NODE_ADDRESS, - GNOSIS_BZZ_ADDRESS, DEFAULT_SWARM_CONFIG, STORAGE_OPTIONS, BEE_GATEWAY_URL, @@ -155,33 +153,6 @@ const SwapComponent: React.FC = () => { const [uploadProgress, setUploadProgress] = useState(0); const [showStampList, setShowStampList] = useState(false); - // Approval options state - const [approvalType, setApprovalType] = useState<'exact' | 'infinite'>('exact'); - const [showApprovalDropdown, setShowApprovalDropdown] = useState(false); - const [needsApproval, setNeedsApproval] = useState(false); - const [isCheckingApproval, setIsCheckingApproval] = useState(false); - const approvalDropdownRef = useRef(null); - - // Close approval dropdown when clicking outside - useEffect(() => { - const handleClickOutside = (event: MouseEvent) => { - if ( - approvalDropdownRef.current && - !approvalDropdownRef.current.contains(event.target as Node) - ) { - setShowApprovalDropdown(false); - } - }; - - if (showApprovalDropdown) { - document.addEventListener('mousedown', handleClickOutside); - } - - return () => { - document.removeEventListener('mousedown', handleClickOutside); - }; - }, [showApprovalDropdown]); - const [isWalletLoading, setIsWalletLoading] = useState(true); const [postageBatchId, setPostageBatchId] = useState(''); const [topUpBatchId, setTopUpBatchId] = useState(null); @@ -540,160 +511,7 @@ const SwapComponent: React.FC = () => { setNodeAddress(address); }, [beeApiUrl]); - // Check if BZZ approval is needed - const checkBzzApproval = useCallback( - async (amount: bigint): Promise => { - if (!address || !publicClient) return true; - - try { - const allowance = await publicClient.readContract({ - address: GNOSIS_BZZ_ADDRESS as `0x${string}`, - abi: parseAbi([ - 'function allowance(address owner, address spender) external view returns (uint256)', - ]), - functionName: 'allowance', - args: [address as `0x${string}`, GNOSIS_CUSTOM_REGISTRY_ADDRESS as `0x${string}`], - }); - - return BigInt(allowance.toString()) < amount; - } catch (error) { - console.error('Failed to check BZZ allowance:', error); - return true; // Default to needing approval if check fails - } - }, - [address, publicClient] - ); - - // Handle BZZ approval - const handleBzzApproval = async () => { - if (!address || !publicClient || !walletClient || !currentPrice || !selectedDays) { - return; - } - - try { - setIsLoading(true); - setShowOverlay(true); - setStatusMessage({ - step: 'Approval', - message: 'Approving BZZ tokens...', - }); - - // Calculate amount based on whether this is a top-up or new batch - let totalAmount: bigint; - if (isTopUp && originalStampInfo) { - totalAmount = calculateTopUpAmount(originalStampInfo.depth); - } else { - const initialPaymentPerChunkPerDay = BigInt(currentPrice) * BigInt(17280); - const totalPricePerDuration = initialPaymentPerChunkPerDay * BigInt(selectedDays); - totalAmount = totalPricePerDuration * BigInt(2 ** selectedDepth); - } - - const MAX_UINT256 = - '115792089237316195423570985008687907853269984665640564039457584007913129639935'; - const approvalAmount = approvalType === 'infinite' ? BigInt(MAX_UINT256) : totalAmount; - - const approveCallData = { - address: GNOSIS_BZZ_ADDRESS as `0x${string}`, - abi: [ - { - constant: false, - inputs: [ - { name: '_spender', type: 'address' }, - { name: '_value', type: 'uint256' }, - ], - name: 'approve', - outputs: [{ name: 'success', type: 'bool' }], - type: 'function', - }, - ], - functionName: 'approve', - args: [GNOSIS_CUSTOM_REGISTRY_ADDRESS, approvalAmount], - account: address, - }; - - const approveTxHash = await walletClient.writeContract(approveCallData); - - setStatusMessage({ - step: 'Approval', - message: 'Waiting for approval confirmation...', - }); - - const approveReceipt = await publicClient.waitForTransactionReceipt({ - hash: approveTxHash, - pollingInterval: getPollingInterval(chainId), - }); - - if (approveReceipt.status !== 'success') { - throw new Error('Approval failed'); - } - - console.log( - `✅ ${approvalType === 'infinite' ? 'Infinite' : 'Exact'} BZZ approval completed successfully` - ); - - // Update approval status - setNeedsApproval(false); - setIsLoading(false); - setShowOverlay(false); - } catch (error) { - console.error('Approval failed:', error); - setStatusMessage({ - step: 'Error', - message: 'Approval failed', - error: error instanceof Error ? error.message : 'Unknown error', - isError: true, - }); - setIsLoading(false); - setShowOverlay(false); - } - }; - - // Check approval status when relevant parameters change - useEffect(() => { - const checkApprovalStatus = async () => { - if ( - selectedChainId === ChainId.DAI && - fromToken && - getAddress(fromToken) === getAddress(GNOSIS_BZZ_ADDRESS) && - currentPrice && - selectedDays && - address && - publicClient - ) { - setIsCheckingApproval(true); - - // Calculate total amount - let totalAmount: bigint; - if (isTopUp && originalStampInfo) { - totalAmount = calculateTopUpAmount(originalStampInfo.depth); - } else { - const initialPaymentPerChunkPerDay = BigInt(currentPrice) * BigInt(17280); - const totalPricePerDuration = initialPaymentPerChunkPerDay * BigInt(selectedDays); - totalAmount = totalPricePerDuration * BigInt(2 ** selectedDepth); - } - - const needsApprovalResult = await checkBzzApproval(totalAmount); - setNeedsApproval(needsApprovalResult); - setIsCheckingApproval(false); - } else { - setNeedsApproval(false); - setIsCheckingApproval(false); - } - }; - - checkApprovalStatus(); - }, [ - selectedChainId, - fromToken, - currentPrice, - selectedDays, - address, - publicClient, - isTopUp, - originalStampInfo, - selectedDepth, - checkBzzApproval, - ]); + // BZZ approval is handled automatically by Relay as part of the swap steps. useEffect(() => { const fetchAndSetNode = async () => { @@ -1426,18 +1244,6 @@ const SwapComponent: React.FC = () => { } }, [topUpBatchId, isTopUp, fetchStampInfoForComponent]); - // Calculate amount for topping up an existing batch - const calculateTopUpAmount = (originalDepth: number) => { - if (currentPrice === null || !selectedDays) return 0n; - - // We use the original depth from the stamp, not the currently selected depth - const initialPaymentPerChunkPerDay = BigInt(currentPrice) * BigInt(17280); - const totalPricePerDuration = initialPaymentPerChunkPerDay * BigInt(selectedDays); - - // Calculate for the original batch depth - return totalPricePerDuration * BigInt(2 ** originalDepth); - }; - // Set hasMounted and badge label by host: LOCAL (localhost), TEST (beeport.xyz), BETA (elsewhere) useEffect(() => { setHasMounted(true); @@ -1617,16 +1423,7 @@ const SwapComponent: React.FC = () => { insufficientFunds || isPriceEstimating) } - onClick={ - !hasMounted || !isConnected - ? handleGetStarted - : selectedChainId === ChainId.DAI && - fromToken && - getAddress(fromToken) === getAddress(GNOSIS_BZZ_ADDRESS) && - needsApproval - ? handleBzzApproval - : handleSwap - } + onClick={!hasMounted || !isConnected ? handleGetStarted : handleSwap} > {isLoading ? (
Loading...
@@ -1646,58 +1443,10 @@ const SwapComponent: React.FC = () => { 'Insufficient Balance' ) : isTopUp ? ( 'Top Up Batch' - ) : selectedChainId === ChainId.DAI && - fromToken && - getAddress(fromToken) === getAddress(GNOSIS_BZZ_ADDRESS) && - needsApproval ? ( -
- {approvalType === 'exact' ? 'Approve' : 'Approve Infinite'} - { - e.stopPropagation(); - setShowApprovalDropdown(!showApprovalDropdown); - }} - > - ▼ - -
) : ( 'Buy Storage' )} - - {/* Approval dropdown positioned relative to the main button */} - {selectedChainId === ChainId.DAI && - fromToken && - getAddress(fromToken) === getAddress(GNOSIS_BZZ_ADDRESS) && - needsApproval && - showApprovalDropdown && ( -
- - -
- )} {executionResult && (