### Fetch Pool Data with GraphQL (TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Fetches individual pool data using a GraphQL query, including details like tokens, liquidity, APR, and staking configuration. This example uses the `useGetPoolQuery` hook from Apollo Client and demonstrates handling loading, error states, and accessing various pool properties. ```typescript import { useGetPoolQuery } from '~/apollo/generated/graphql-codegen-generated'; function PoolDetailPage({ poolId }: { poolId: string }) { const { data, loading, error, refetch } = useGetPoolQuery({ variables: { id: poolId }, pollInterval: 30000, // Poll every 30 seconds }); if (loading) return
Loading pool data...
; if (error) return
Error loading pool: {error.message}
; const pool = data?.pool; if (!pool) return
Pool not found
; // Access pool properties const totalLiquidity = pool.dynamicData.totalLiquidity; const volume24h = pool.dynamicData.volume24h; const totalApr = pool.dynamicData.apr.apr.__typename === 'GqlPoolAprTotal' ? pool.dynamicData.apr.apr.total : pool.dynamicData.apr.apr.max; // Get pool tokens const tokens = pool.__typename === 'GqlPoolWeighted' ? pool.tokens : pool.tokens; // Check staking configuration const hasStaking = !!pool.staking; const stakingType = pool.staking?.type; // 'MASTER_CHEF' | 'GAUGE' | 'RELIQUARY' return (

{pool.name}

Total Liquidity: ${totalLiquidity}

24h Volume: ${volume24h}

APR: {totalApr}%

Tokens

{hasStaking &&

Staking Type: {stakingType}

}
); } ``` -------------------------------- ### Get Pool Service for Weighted Pool - TypeScript Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Factory function to retrieve the appropriate service handler for a given pool type, enabling specific calculations for joins, exits, and price impacts. It takes a GqlPoolUnion object as input and returns a pool service instance. Dependencies include '~/lib/services/pool/pool-util' and '~/apollo/generated/graphql-codegen-generated'. ```typescript import { poolGetServiceForPool } from '~/lib/services/pool/pool-util'; import { GqlPoolUnion } from '~/apollo/generated/graphql-codegen-generated'; // Example: Get service for a weighted pool const pool: GqlPoolUnion = { __typename: 'GqlPoolWeighted', id: '0x...', address: '0x...', version: 2, nestingType: 'NO_NESTING', tokens: [...], // ... other pool properties }; const poolService = poolGetServiceForPool(pool); // Now you can use pool-specific methods const { bptOut, priceImpact } = await poolService.joinGetBptOutAndPriceImpactForTokensIn({ tokenAmountsIn: [ { address: '0xtoken1...', amount: '1000000000000000000' }, // 1.0 tokens { address: '0xtoken2...', amount: '2000000000000000000' }, // 2.0 tokens ], }); console.log(`Expected BPT output: ${bptOut}`); console.log(`Price impact: ${priceImpact}%`); // Get contract call data for the join const callData = await poolService.joinGetContractCallData({ tokenAmountsIn: [ { address: '0xtoken1...', amount: '1000000000000000000' }, { address: '0xtoken2...', amount: '2000000000000000000' }, ], minBptOut: bptOut, // Could apply slippage here kind: 'ExactTokensInForBPTOut', }); // Returns: { type: 'JoinPool', to: vaultAddress, data: encodedCallData, value: '0' } ``` -------------------------------- ### Wallet Connection and User State Management with wagmi and Apollo Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt This snippet demonstrates how to connect a user's wallet using wagmi, manage connection states, and automatically sync wallet data with Apollo Client for GraphQL queries. It uses custom hooks to handle the integration, updating reactive variables to trigger data refetches. ```typescript import { useAccount, useConnect, useDisconnect } from 'wagmi'; import { ConnectButton } from '@rainbow-me/rainbowkit'; // The application provides useUserAccount hook that integrates wagmi with Apollo function WalletConnection() { const { address, isConnected } = useAccount(); const { connect, connectors } = useConnect(); const { disconnect } = useDisconnect(); // Custom hook that syncs wallet state with Apollo Client // Located at: lib/global/useUserAccount.ts // This automatically updates the userAddressVar reactive variable // which triggers re-fetches of user-specific queries return (
{!isConnected ? (

Connect Your Wallet

{/* Or manual connection: */} {connectors.map(connector => ( ))}
) : (

Connected: {address}

)}
); } // Example of a component that uses connected user data function UserDashboard() { const { address } = useAccount(); const { data: userData } = useGetUserDataQuery({ skip: !address, }); if (!address) { return ; } const balances = userData?.balances || []; const totalValueUSD = balances.reduce((sum, b) => { return sum + (parseFloat(b.totalBalance) * parseFloat(b.tokenPrice)); }, 0); return (

Dashboard

Address: {address}

Total Portfolio Value: ${totalValueUSD.toFixed(2)}

Active Positions: {balances.length}

); } ``` -------------------------------- ### Fetch and Display Pool Snapshots (TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Fetches historical pool snapshots and BPT price data for the last 30 days using Apollo GraphQL hooks. It then transforms and displays this data as summary statistics, liquidity charts, BPT price history, and a table of recent snapshots. Dependencies include Apollo hooks for querying and React for rendering. ```typescript import { useGetPoolSnapshotsQuery, useGetPoolBptPriceChartDataQuery, GqlPoolSnapshotDataRange, GqlTokenChartDataRange } from '~/apollo/generated/graphql-codegen-generated'; function PoolCharts({ poolId, poolAddress }: { poolId: string; poolAddress: string }) { // Fetch pool metrics snapshots const { data: snapshotData } = useGetPoolSnapshotsQuery({ variables: { poolId: poolId, range: GqlPoolSnapshotDataRange.ThirtyDays }, }); // Fetch BPT price history const { data: priceData } = useGetPoolBptPriceChartDataQuery({ variables: { address: poolAddress, range: GqlTokenChartDataRange.ThirtyDays, }, }); const snapshots = snapshotData?.snapshots || []; const prices = priceData?.prices || []; // Transform data for charting const chartData = snapshots.map(snapshot => ({ timestamp: new Date(snapshot.timestamp * 1000).toLocaleDateString(), liquidity: parseFloat(snapshot.totalLiquidity), volume: parseFloat(snapshot.volume24h), fees: parseFloat(snapshot.fees24h), sharePrice: parseFloat(snapshot.sharePrice), })); // Calculate statistics const totalVolume = snapshots.reduce((sum, s) => sum + parseFloat(s.volume24h), 0); const totalFees = snapshots.reduce((sum, s) => sum + parseFloat(s.fees24h), 0); const avgLiquidity = snapshots.reduce((sum, s) => sum + parseFloat(s.totalLiquidity), 0) / snapshots.length; // BPT price chart data const bptPriceChart = prices.map(p => ({ timestamp: new Date(p.timestamp * 1000).toLocaleDateString(), price: parseFloat(p.price), })); return (

Pool Analytics (Last 30 Days)

Summary Statistics

Total Volume: ${totalVolume.toFixed(2)}

Total Fees: ${totalFees.toFixed(2)}

Average Liquidity: ${avgLiquidity.toFixed(2)}

Liquidity Over Time

{JSON.stringify(chartData, null, 2)}

BPT Price History

{JSON.stringify(bptPriceChart, null, 2)}

Recent Snapshots

{snapshots.slice(-7).reverse().map(snapshot => ( ))}
Date Liquidity Volume 24h Fees 24h Share Price
{new Date(snapshot.timestamp * 1000).toLocaleDateString()} ${parseFloat(snapshot.totalLiquidity).toFixed(2)} ${parseFloat(snapshot.volume24h).toFixed(2)} ${parseFloat(snapshot.fees24h).toFixed(2)} ${parseFloat(snapshot.sharePrice).toFixed(6)}
); } ``` -------------------------------- ### Fetch User Portfolio Data using TypeScript Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Fetches and displays a user's cryptocurrency portfolio data, including pool balances, staking positions, and Fresh Beets (fBeets) holdings. It relies on the 'useGetUserDataQuery' hook for data retrieval and 'useUserAccount' for the user's wallet address. The component handles loading states and displays calculated total portfolio value and individual holdings. ```typescript import { useGetUserDataQuery } from '~/apollo/generated/graphql-codegen-generated'; import { useUserAccount } from '~/lib/global/useUserAccount'; function UserPortfolio() { const { userAddress } = useUserAccount(); const { data, loading } = useGetUserDataQuery({ skip: !userAddress, pollInterval: 30000, }); if (!userAddress) return
Please connect wallet
; if (loading) return
Loading portfolio...
; const balances = data?.balances || []; const staking = data?.staking || []; const fbeetsBalance = data?.fbeetsBalance; // Calculate total portfolio value const totalValue = balances.reduce((sum, balance) => { const value = parseFloat(balance.totalBalance) * parseFloat(balance.tokenPrice); return sum + value; }, 0); // Get staked positions const stakedPositions = staking.filter(stake => stake.type === 'GAUGE'); return (

My Portfolio

Total Value: ${totalValue.toFixed(2)}

Pool Balances

{fbeetsBalance && (

Fresh Beets (fBEETS)

Total: {fbeetsBalance.totalBalance}

Staked: {fbeetsBalance.stakedBalance}

Wallet: {fbeetsBalance.walletBalance}

)}

Active Staking ({stakedPositions.length})

); } ``` -------------------------------- ### Fetch User Token Balances with Wagmi Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Queries on-chain token balances for a connected wallet address using wagmi for account management and a custom token service. It defines a list of tokens to query, adds them to the service, fetches balances, and logs them. Dependencies include wagmi, and a local token service implementation. ```typescript import { tokenService } from '~/lib/services/token/token.service'; import { TokenBase } from '~/lib/services/token/token-types'; import { useAccount } from 'wagmi'; async function fetchUserTokenBalances() { const { address } = useAccount(); if (!address) { console.log('No wallet connected'); return; } // Define tokens to check const tokens: TokenBase[] = [ { address: '0x04068da6c83afcfa0e13ba15a6696662335d5b75', symbol: 'USDC', decimals: 6, name: 'USD Coin' }, { address: '0x8d11ec38a3eb5e956b052f67da8bdc9bef8abf3e', symbol: 'DAI', decimals: 18, name: 'Dai Stablecoin' }, { address: '0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83', symbol: 'WFTM', decimals: 18, name: 'Wrapped Fantom' }, { address: '0xf24bcf4d1e507740041c9cfd2dddb29585adce1e', symbol: 'BEETS', decimals: 18, name: 'Beethoven X' }, ]; // Load token data into service tokenService.addTokens(tokens); // Fetch balances const balances = await tokenService.getBalancesForAccount(address, tokens); console.log('Token Balances:'); balances.forEach(balance => { const token = tokens.find(t => t.address === balance.address); console.log(`${token?.symbol}: ${balance.amount} (${token?.decimals} decimals)`); }); return balances; // Example output: // USDC: 1500.50 // DAI: 2000.123456 // WFTM: 100.0 // BEETS: 500.0 } // React component example function UserBalances() { const { address } = useAccount(); const [balances, setBalances] = React.useState([]); const [loading, setLoading] = React.useState(false); const loadBalances = async () => { if (!address) return; setLoading(true); try { const result = await fetchUserTokenBalances(); setBalances(result || []); } catch (error) { console.error('Error loading balances:', error); } finally { setLoading(false); } }; React.useEffect(() => { loadBalances(); }, [address]); if (!address) return
Connect wallet to view balances
; if (loading) return
Loading balances...
; return (

Your Token Balances

    {balances.map(balance => (
  • {balance.address.slice(0, 10)}...: {balance.amount}
  • ))}
); } ``` -------------------------------- ### Fetch Global Application Data with Apollo Hooks (React/TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Fetches essential global application data, including token lists, protocol metrics, and blockchain parameters, using Apollo GraphQL hooks. It distinguishes between static data fetched once on mount (`useGetAppGlobalDataQuery`) and dynamic data polled periodically (`useGetAppGlobalPollingDataQuery`). The data is then processed and made available via a React Context. ```typescript import { useGetAppGlobalDataQuery, useGetAppGlobalPollingDataQuery } from '~/apollo/generated/graphql-codegen-generated'; function AppDataProvider({ children }: { children: React.ReactNode }) { // Fetch static data once on mount const { data: globalData, loading: globalLoading } = useGetAppGlobalDataQuery(); // Poll dynamic data every 30 seconds const { data: pollingData } = useGetAppGlobalPollingDataQuery({ pollInterval: 30000, }); if (globalLoading) return
Loading application data...
; const tokens = globalData?.tokenGetTokens || []; const fbeetsRatio = globalData?.beetsGetFbeetsRatio || '0'; const blocksPerDay = globalData?.blocksGetBlocksPerDay || 0; const veBALTotalSupply = globalData?.veBALTotalSupply || '0'; // Get real-time prices const tokenPrices = pollingData?.tokenGetCurrentPrices || []; const protocolMetrics = pollingData?.protocolMetricsChain; const beetsPrice = pollingData?.tokenGetProtocolTokenPrice || 0; // Create price map for easy lookup const priceMap = tokenPrices.reduce((acc, tp) => { acc[tp.address] = parseFloat(tp.price); return acc; }, {} as Record); console.log(`Total tokens available: ${tokens.length}`); console.log(`BEETS price: $${beetsPrice}`); console.log(`Fresh BEETS ratio: ${fbeetsRatio}`); console.log(`Blocks per day: ${blocksPerDay}`); if (protocolMetrics) { console.log(`Total Protocol Liquidity: $${protocolMetrics.totalLiquidity}`); console.log(`24h Volume: $${protocolMetrics.swapVolume24h}`); console.log(`24h Fees: $${protocolMetrics.swapFee24h}`); console.log(`Total Pools: ${protocolMetrics.poolCount}`); } // Example: Get price for specific token const getTokenPrice = (address: string) => { return priceMap[address.toLowerCase()] || 0; }; const usdcAddress = '0x04068da6c83afcfa0e13ba15a6696662335d5b75'; console.log(`USDC Price: $${getTokenPrice(usdcAddress)}`); return ( {children} ); } ``` -------------------------------- ### ERC-20 Token Approval Management Hook Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt This TypeScript hook, `useApproveToken`, facilitates the management of ERC-20 token approvals. It handles the approval process, provides loading and success states, tracks current allowances, and includes error handling. Dependencies include a network configuration utility. ```typescript import { useApproveToken } from '~/lib/util/useApproveToken'; import { networkConfig } from '~/lib/config/network-config'; function TokenApprovalExample() { const tokenAddress = '0xusdc...'; const spenderAddress = networkConfig.balancer.vault; const amountToApprove = '1000000000'; // 1000 USDC (6 decimals) const { approve, isApproving, isApproved, currentAllowance, refetch: refetchAllowance, } = useApproveToken({ tokenAddress, spenderAddress, amount: amountToApprove, }); const handleApprove = async () => { try { await approve(); console.log('Token approved successfully'); // Approval successful, proceed with transaction await performPoolJoin(); } catch (error) { console.error('Approval failed:', error); } }; const needsApproval = parseFloat(currentAllowance) < parseFloat(amountToApprove); return (

Token Approval Status

Token: {tokenAddress}

Spender: {spenderAddress}

Current Allowance: {currentAllowance}

Required Amount: {amountToApprove}

{needsApproval ? ( ) : (

✓ Token already approved

)} {isApproved &&

✓ Approval confirmed!

}
); } // Example: Approval flow before pool investment async function investWithApproval() { const tokens = [ { address: '0xusdc...', amount: '1000000000' }, { address: '0xdai...', amount: '1000000000000000000000' }, ]; // Check and approve each token for (const token of tokens) { const { approve, isApproved } = useApproveToken({ tokenAddress: token.address, spenderAddress: networkConfig.balancer.vault, amount: token.amount, }); if (!isApproved) { await approve(); // Wait for approval confirmation } } // All tokens approved, proceed with investment console.log('All tokens approved, executing pool join...'); } ``` -------------------------------- ### Convert Token Amounts: Human to Scaled and Back (TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Converts token amounts between human-readable strings and blockchain-scaled numbers (using BigNumber) based on token decimals. It also demonstrates converting back to human-readable format. Requires the tokenService to be initialized with token details. ```typescript import { tokenService } from '~/lib/services/token/token.service'; import { TokenBase, TokenAmountHumanReadable } from '~/lib/services/token/token-types'; // First, ensure tokens are loaded into the service const tokens: TokenBase[] = [ { address: '0xusdc...', symbol: 'USDC', decimals: 6, name: 'USD Coin' }, { address: '0xdai...', symbol: 'DAI', decimals: 18, name: 'Dai Stablecoin' }, ]; tokenService.addTokens(tokens); // Convert human-readable amounts to scaled (wei) amounts const humanReadableAmounts: TokenAmountHumanReadable[] = [ { address: '0xusdc...', amount: '100.50' }, // 100.50 USDC { address: '0xdai...', amount: '1500.123456' }, // 1500.123456 DAI ]; const scaledAmounts = tokenService.humanReadableToScaled(humanReadableAmounts); console.log(scaledAmounts); // [ // { address: '0xusdc...', amount: BigNumber(100500000) }, // 6 decimals // { address: '0xdai...', amount: BigNumber(1500123456000000000000) } // 18 decimals // ] // Convert back to human-readable const backToHuman = tokenService.scaledToHumanReadable(scaledAmounts); console.log(backToHuman); // [ // { address: '0xusdc...', amount: '100.5' }, // { address: '0xdai...', amount: '1500.123456' } // ] ``` -------------------------------- ### Pool Context Hook for Pool Interaction Components (TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Provides a React context hook ('usePool') that offers comprehensive pool data, service methods for interaction, and metadata. The 'PoolProvider' wraps components that need access to this context. Child components can then consume the pool data and use the 'poolService' for operations like calculating join amounts. ```typescript import { usePool, PoolProvider } from '~/modules/pool/lib/usePool'; import { GqlPoolUnion } from '~/apollo/generated/graphql-codegen-generated'; // Wrap your pool components with PoolProvider function PoolPage({ initialPool }: { initialPool: GqlPoolUnion }) { return ( ); } // Use pool data in child components function PoolDetails() { const { pool, poolService, bpt, bptPrice, allTokens, requiresBatchRelayerOnJoin, supportsZap, formattedTypeName, totalApr, isFbeetsPool, isStablePool, isComposablePool, } = usePool(); console.log(`Pool Type: ${formattedTypeName}`); console.log(`BPT Price: $${bptPrice.toFixed(4)}`); console.log(`Total APR: ${totalApr.toFixed(2)}%`); console.log(`Requires Batch Relayer: ${requiresBatchRelayerOnJoin}`); console.log(`Supports Zap: ${supportsZap}`); // Use pool service for calculations const handleCalculateJoin = async () => { const result = await poolService.joinGetBptOutAndPriceImpactForTokensIn({ tokenAmountsIn: [ { address: allTokens[0].address, amount: '1000000000000000000' }, ], }); console.log(`Expected BPT: ${result.bptOut}`); console.log(`Price Impact: ${result.priceImpact}%`); }; return (

{pool.name} ({pool.symbol})

{formattedTypeName}

TVL: ${pool.dynamicData.totalLiquidity}

APR: {totalApr.toFixed(2)}%

BPT Address: {bpt.address}

{isComposablePool &&

⚠️ This is a composable pool (nested tokens)

} {isFbeetsPool &&

🎵 This is the Fresh Beets pool

}

Tokens ({allTokens.length})

    {allTokens.map(token => (
  • {token.symbol} ({token.decimals} decimals)
  • ))}
); } ``` -------------------------------- ### Submit Transaction with Status Tracking - TypeScript Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt A custom hook for executing blockchain transactions, featuring automatic toast notifications, real-time transaction tracking, and robust error handling. It simplifies the process of submitting transactions and updating the UI based on their status. Dependencies include '~/lib/util/useSubmitTransaction'. ```typescript import { useSubmitTransaction, vaultContractConfig } from '~/lib/util/useSubmitTransaction'; function PoolInvestComponent() { const transaction = useSubmitTransaction({ config: { ...vaultContractConfig, functionName: 'joinPool', onSettled: () => { // Refetch balances after transaction completes refetchUserData(); }, }, transactionType: 'INVEST', }); const handleInvest = async () => { // Prepare call data const joinPoolRequest = { poolId: '0x...', sender: userAddress, recipient: userAddress, assets: ['0xtoken1...', '0xtoken2...'], maxAmountsIn: ['1000000000000000000', '2000000000000000000'], userData: encodedUserData, fromInternalBalance: false, }; // Submit the transaction transaction.submit({ args: [ joinPoolRequest.poolId, joinPoolRequest.sender, joinPoolRequest.recipient, joinPoolRequest, ], toastText: 'Investing in liquidity pool', walletText: 'Invest 1 TOKEN1 + 2 TOKEN2', }); }; return (
{transaction.isPending &&

Transaction pending...

} {transaction.isConfirmed &&

Investment successful!

} {transaction.isFailed &&

Transaction failed: {transaction.error?.message}

}
); } ``` -------------------------------- ### Format Numbers for Display and Input Validation (TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Provides utility functions for formatting currency values, large numbers with suffixes (k, m, b), and limiting decimal places for user inputs. It also includes a function to scale numbers for blockchain representations, often used with libraries like BigNumber.js. These are essential for presenting financial data clearly and ensuring accurate user input. ```typescript import { numberFormatUSDValue, numberFormatLargeUsdValue, numberFormatLargeValue, numberLimitInputToNumDecimals, scale } from '~/lib/util/number-formats'; import BigNumber from 'bignumber.js'; // Format USD values with appropriate precision console.log(numberFormatUSDValue(0.00005)); // "$0.00" console.log(numberFormatUSDValue(0.05)); // "$0.05" console.log(numberFormatUSDValue(0.5)); // "$0.50" console.log(numberFormatUSDValue(5.123)); // "$5.12" console.log(numberFormatUSDValue(1234.56)); // "$1,234.56" console.log(numberFormatUSDValue(12345)); // "$12,345" // Format large USD values with suffixes console.log(numberFormatLargeUsdValue(1234)); // "$1.23k" console.log(numberFormatLargeUsdValue(1234567)); // "$1.23m" console.log(numberFormatLargeUsdValue(1234567890)); // "$1.23b" // Format large numbers without USD console.log(numberFormatLargeValue(999)); // "999" console.log(numberFormatLargeValue(12345)); // "12.35k" console.log(numberFormatLargeValue(1234567)); // "1.23m" // Limit decimal places in user input (e.g., for input validation) const userInput = "123.456789012345678901"; console.log(numberLimitInputToNumDecimals(userInput, 18)); // "123.456789012345678901" console.log(numberLimitInputToNumDecimals(userInput, 6)); // "123.456789" console.log(numberLimitInputToNumDecimals(userInput, 2)); // "123.45" // Scale numbers for blockchain (convert to wei-like representation) const amount = new BigNumber("1.5"); const scaled = scale(amount, 18); // Scale to 18 decimals console.log(scaled.toString()); // "1500000000000000000" // Can also pass string directly const scaledFromString = scale("2.5", 6); // Scale to 6 decimals (e.g., USDC) console.log(scaledFromString.toString()); // "2500000" ``` -------------------------------- ### Encode Complex Pool Join with Balancer Batch Relayer (TypeScript) Source: https://context7.com/beethovenxfi/beets-frontend/llms.txt Encodes a sequence of operations for joining a Balancer pool, including wrapping ETH to WETH, performing the pool join with specified amounts, and staking the resulting BPT in a gauge. This function relies on the `batchRelayerService` and `useSubmitTransaction` hook for execution. ```typescript import { batchRelayerService } from '~/lib/services/batch-relayer/batch-relayer.service'; import { batchRelayerContractConfig } from '~/lib/util/useSubmitTransaction'; async function executeComplexPoolJoin() { const userAddress = '0xuser...'; const poolAddress = '0xpool...'; const poolId = '0xpoolId...'; // Step 1: Wrap ETH to WETH const wrapCall = batchRelayerService.vaultActionsService.encodeWrap( '0xweth...', '0xuser...', '0', // Output reference for chained calls '1000000000000000000', // 1 ETH ); // Step 2: Join pool with wrapped WETH const joinCall = await batchRelayerService.encodeJoinPool({ poolId: poolId, poolAddress: poolAddress, tokens: ['0xweth...', '0xusdc...'], sender: userAddress, recipient: userAddress, kind: 'Init', amountsIn: [ '1000000000000000000', // 1 WETH (from wrap) '1000000000', // 1000 USDC ], minBptOut: '0', // Slippage protection fromInternalBalance: false, }); // Step 3: Stake BPT in gauge const stakeCall = batchRelayerService.encodeGaugeDeposit({ gauge: '0xgauge...', sender: userAddress, recipient: userAddress, amount: '0', // Use output from join outputReference: '0', }); // Combine all calls const calls = [wrapCall, joinCall, stakeCall]; // Execute via transaction hook const transaction = useSubmitTransaction({ config: { ...batchRelayerContractConfig, onSettled: () => console.log('Complex join completed'), }, transactionType: 'INVEST', }); transaction.submit({ args: [calls], overrides: { value: '1000000000000000000' }, // Send 1 ETH toastText: 'Wrapping ETH, joining pool, and staking', walletText: 'Wrap + Join + Stake', }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.