### 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
);
}
```
--------------------------------
### 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 (
);
}
```
--------------------------------
### 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
);
}
```
--------------------------------
### 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
);
}
// 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.