# Introduction
Source: https://docs.solanaappkit.com/docs/introduction
Open-source React Native scaffold for building iOS and Android crypto mobile apps with seamless Solana protocol integrations
Welcome to **Solana App Kit** - an open-source React Native scaffold for building iOS and Android crypto mobile apps with seamless Solana protocol integrations.
## What is Solana App Kit?
Solana App Kit is a comprehensive mobile app development framework that provides everything you need to build production-ready Solana applications. Whether you're a seasoned React Native developer or a Solana developer looking to enter mobile development, this kit enables you to build feature-rich apps in under 15 minutes.
**Quick Start**: Get your first Solana mobile app running with just `npx start-solana-app`
## Key Features
Complete mobile app scaffold with iOS and Android support, production-ready codebase, and minimal configuration
Ready-to-use integrations with 10+ major Solana protocols including Jupiter, Raydium, Pump.fun, and more
Independent modules that allow you to use only what you need while maintaining clean code separation
Built specifically for mobile with native performance, responsive UI, and touch-optimized interactions
## Protocol Integrations
The kit includes ready-to-use integrations with major Solana protocols:
**Best-in-class DEX aggregator** for optimal swap prices across all Solana DEXs
**Native AMM integration** for meme token creation and viral trading
**Direct integration** with Raydium's concentrated liquidity pools
**Meme token creation** and community-driven trading platform
**Professional token launching** with advanced liquidity management
**Advanced DeFi token launches** with dynamic liquidity markets
**Custom token creation** with configurable bonding curves and tokenomics
**Embedded wallets** with social login (Google, Apple, Twitter)
**Multi-chain wallet connections** with 300+ wallet support
**Enterprise-grade wallet infrastructure** with MPC security
**Native Solana Mobile** wallet support with deep linking
**Enhanced RPC** and transaction data with better reliability
**Real-time token prices** and comprehensive market analytics
**Market data** and token information from the leading crypto data provider
**Token safety analysis** and security scoring for user protection
**NFT minting** and metadata management with industry standards
**NFT trading marketplace** integration with advanced analytics
**AI-powered Solana interactions** with natural language processing
**Fiat on/off-ramps** with Apple Pay and credit card support
**MEV protection** and optimized transaction landing
## Who Is This For?
Jump into Solana development without learning blockchain from scratch. Leverage familiar patterns and focus on user experience.
Extend your reach to mobile platforms using pre-built UI components without learning React Native from scratch.
Rapidly prototype and launch Solana-based mobile apps, reducing development time from months to weeks.
## What Can You Build?
**Multi-DEX trading platforms** with optimal routing, real-time prices, and advanced order types. Perfect for building the next generation of mobile trading experiences.
*Example features: Cross-DEX arbitrage, automated trading strategies, portfolio analytics*
**Community-driven token creation** and viral trading platforms. Build the infrastructure for the next big meme token ecosystem.
*Example features: One-click token launches, viral sharing mechanisms, community governance*
**Combine social features with token interactions** for community-driven investing and shared trading experiences.
*Example features: Trading feeds, copy trading, social sentiment analysis*
**Create, trade, and showcase digital collectibles** with advanced marketplace features and collection management.
*Example features: NFT creation tools, marketplace integration, collection analytics*
**Full-featured mobile wallets** with multiple provider support and advanced security features.
*Example features: Multi-wallet support, transaction history, security settings*
**Integrate AI agents** for automated Solana interactions and intelligent trading assistance.
*Example features: Natural language trading, portfolio optimization, market analysis*
**Fiat on-ramps and crypto payment solutions** for mainstream adoption and easy onboarding.
*Example features: Apple Pay integration, merchant payments, multi-currency support*
## Architecture Overview
The kit consists of two main components that work together seamlessly:
**Cross-platform mobile framework** for iOS and Android with native performance
**Full type safety** and enhanced developer experience with intelligent autocompletion
**Predictable state management** with time-travel debugging and persistence
**Smooth navigation** between screens with gesture support and deep linking
**RESTful API server** with middleware support and robust routing
**Reliable data persistence** with ACID compliance and scalability
**Google Cloud Storage and IPFS** support for decentralized file storage
**WebSocket support** for live updates and real-time collaboration
## Getting Started
The fastest way to get started is with our CLI tool:
```bash
npx start-solana-app
```
This command will:
* Clone the repository
* Install all dependencies
* Set up your development environment
* Launch the app on your device or simulator
For detailed setup instructions, continue to the [Setup Guide](/docs/setup)
**Pro Tip**: The entire setup process takes less than 5 minutes on most machines!
## Community & Support
Join our growing community of Solana mobile developers:
**@solanaappkit** - Get real-time help and connect with other developers
**@solanaappkit** - Latest updates, tips, and community highlights
**SendArcade/solana-app-kit** - Contribute, report issues, and explore the code
## What's Next?
Ready to start building? Here's your roadmap:
**Install and configure** your development environment with step-by-step instructions
**Understand the codebase** organization and learn how everything fits together
**Explore available modules** and discover what you can build with each integration
**See practical examples** and common patterns for building real applications
**New to Solana?** Don't worry! The kit is designed to be beginner-friendly while remaining powerful for experienced developers.
***
# Data Module
Source: https://docs.solanaappkit.com/docs/modules/data-module
Comprehensive blockchain data fetching and management for Solana assets, tokens, NFTs, and market information
The Data Module is your central hub for fetching, processing, and managing on-chain and off-chain data related to Solana assets. It provides seamless integration with multiple data sources including Helius, Birdeye, and CoinGecko.
## Core Functionalities
Fetch token metadata, balances, prices, and historical price data from multiple sources
Retrieve user portfolio assets including NFTs and compressed NFTs (cNFTs)
Access comprehensive market data from CoinGecko including OHLC and market details
Fetch and process user swap transaction history with enriched metadata
## Installation & Setup
Configure your API keys in `.env.local`:
```bash
HELIUS_API_KEY=your_helius_api_key
BIRDEYE_API_KEY=your_birdeye_api_key
COINGECKO_API_KEY=your_coingecko_api_key
```
Import the hooks and services you need:
```typescript
import {
useFetchTokens,
useTokenDetails,
useCoingecko
} from '@/modules/data-module';
```
Use the hooks in your components to fetch data
## Module Architecture
```
src/modules/data-module/
├── services/ # Core API integration logic
├── hooks/ # React hooks for UI integration
├── types/ # TypeScript definitions
├── utils/ # Helper functions
└── index.ts # Public API exports
```
## Core Services
**`tokenService.ts`** - Core token data operations
```typescript
// Key functions available
fetchTokenBalance(walletPublicKey, tokenInfo)
fetchTokenPrice(tokenInfo)
ensureCompleteTokenInfo(token)
estimateTokenUsdValue(amount, decimals, mint, symbol)
fetchTokenList(params)
searchTokens(params)
```
**`coingeckoService.ts`** - Market data from CoinGecko
```typescript
// Available functions
getCoinList()
getCoinMarkets(coinId)
getCoinOHLC(coinId, days)
getBatchCoinMarkets(coinIds)
```
**`tokenDetailsService.ts`** - Comprehensive token information
```typescript
// Birdeye integration
fetchPriceHistory(tokenAddress, timeframe)
fetchTokenOverview(tokenAddress)
fetchTokenSecurity(tokenAddress)
fetchMarketData(tokenAddress)
fetchTradeData(tokenAddress)
```
**`swapTransactions.ts`** - Transaction history
```typescript
// Helius integration
fetchRecentSwaps(walletAddress)
enrichSwapTransactions(swaps)
```
## Essential Hooks
### useFetchTokens()
Fetches all fungible tokens in a user's wallet with portfolio data.
```typescript
import { useFetchTokens } from '@/modules/data-module';
function UserTokenList() {
const { tokens, loading, error, refetch } = useFetchTokens(walletAddress);
if (loading) return Loading tokens...;
if (error) return Error: {error};
return (
(
)}
onRefresh={refetch}
/>
);
}
```
**Returns:**
* `tokens` - Array of user's tokens
* `loading` - Loading state
* `error` - Error message if any
* `refetch` - Function to refresh data
### useTokenDetails()
Comprehensive token information for detail views.
```typescript
import { useTokenDetails } from '@/modules/data-module';
function TokenDetailScreen({ tokenAddress }) {
const {
priceHistory,
metadata,
tokenOverview,
loading,
selectedTimeframe,
handleTimeframeChange
} = useTokenDetails({
tokenAddress,
visible: true
});
return (
);
}
```
**Parameters:**
* `tokenAddress` - Token mint address
* `visible` - Whether to actively fetch data
**Returns:**
* `priceHistory` - Historical price data
* `metadata` - Token metadata
* `tokenOverview` - Overview information
* `loading` - Loading states
* `selectedTimeframe` - Current timeframe
* `handleTimeframeChange` - Timeframe selector
### useCoingecko()
Access CoinGecko market data with caching.
```typescript
import { useCoingecko } from '@/modules/data-module';
function MarketDataComponent() {
const {
coinList,
searchCoins,
searchResults,
fetchCoinData,
loadingCoinList
} = useCoingecko();
const handleSearch = (query) => {
searchCoins(query);
};
return (
);
}
```
### useTokenSearch()
Debounced token search with pagination.
```typescript
import { useTokenSearch } from '@/modules/data-module';
function TokenSearchComponent() {
const {
tokens,
loading,
searchQuery,
setSearchQuery,
loadMore,
refresh
} = useTokenSearch('', 300); // 300ms debounce
return (
}
/>
);
}
```
## Quick Start Example
```typescript Basic Token Display
import { useFetchTokens, TokenInfo } from '@/modules/data-module';
import { useWallet } from '@/modules/wallet-providers';
function UserTokenPortfolio() {
const { wallet } = useWallet();
const { tokens, loading, error, refetch } = useFetchTokens(wallet?.address);
if (loading) return ;
if (error) return ;
return (
item.address}
renderItem={({ item }) => (
{item.name}{item.symbol}{item.balance}
)}
/>
);
}
```
```typescript Market Data Integration
import { useCoingecko } from '@/modules/data-module';
function MarketOverview() {
const {
coinList,
fetchCoinData,
marketCap,
loadingCoinList
} = useCoingecko();
useEffect(() => {
fetchCoinData(['solana', 'bitcoin', 'ethereum']);
}, []);
return (
Total Market Cap: ${marketCap}
{loadingCoinList ? (
) : (
)}
);
}
```
```typescript Token Details View
import { useTokenDetails } from '@/modules/data-module';
function TokenDetailModal({ tokenAddress, visible }) {
const {
priceHistory,
metadata,
tokenOverview,
selectedTimeframe,
handleTimeframeChange,
loading
} = useTokenDetails({ tokenAddress, visible });
return (
);
}
```
## Utility Functions
**`tokenUtils.ts`** - Token formatting and display helpers
```typescript
formatTokenAmount(amount, decimals)
getTokenLogo(tokenAddress)
formatUsdValue(value)
```
**`fetch.ts`** - Robust API calling with retry logic
```typescript
fetchWithRetries(url, options, retries)
fetchUserAssets(walletAddress)
fetchSolBalance(walletAddress)
```
**`tokenDetailsFormatters.ts`** - UI formatting functions
```typescript
formatPrice(price)
formatPriceChange(change)
formatNumber(number)
```
## Data Sources Integration
**Primary Use**: RPC calls, transaction history, asset fetching
* Enhanced Solana RPC
* Transaction parsing
* Asset metadata
**Primary Use**: Token prices, security analysis, market data
* Real-time prices
* Security scoring
* Trade data
* Price history
**Primary Use**: Market information, coin listings
* Coin directories
* Market cap data
* OHLC data
* Global statistics
## Advanced Usage Patterns
### Custom Data Fetching
```typescript
import { tokenService } from '@/modules/data-module';
// Custom token price fetching with fallback
async function getTokenPriceWithFallback(tokenInfo) {
try {
// Try Birdeye first
const price = await tokenService.fetchTokenPrice(tokenInfo);
return price;
} catch (error) {
// Fallback to Jupiter
return await fetchJupiterPrice(tokenInfo.address);
}
}
```
### Batch Data Operations
```typescript
import { coingeckoService } from '@/modules/data-module';
// Fetch multiple coin data efficiently
async function fetchPortfolioMarketData(tokenAddresses) {
const coinIds = await mapAddressesToCoinIds(tokenAddresses);
const marketData = await coingeckoService.getBatchCoinMarkets(coinIds);
return marketData;
}
```
### Real-time Price Updates
```typescript
function useRealTimeTokenPrice(tokenAddress) {
const [price, setPrice] = useState(null);
useEffect(() => {
const interval = setInterval(async () => {
const newPrice = await tokenService.fetchTokenPrice({ address: tokenAddress });
setPrice(newPrice);
}, 10000); // Update every 10 seconds
return () => clearInterval(interval);
}, [tokenAddress]);
return price;
}
```
## Error Handling
**API Rate Limits**: Be mindful of rate limits when making frequent requests. The module includes retry logic but respect provider limits.
```typescript
function TokenDataWithErrorHandling() {
const { tokens, loading, error } = useFetchTokens(walletAddress);
if (error) {
// Handle different error types
if (error.includes('rate limit')) {
return ;
}
if (error.includes('network')) {
return ;
}
return ;
}
return ;
}
```
## Performance Optimization
**Caching**: The module implements intelligent caching for CoinGecko data and token metadata to reduce API calls.
```typescript
// Use debounced search to avoid excessive API calls
const { tokens, setSearchQuery } = useTokenSearch('', 500); // 500ms debounce
// Implement virtual scrolling for large token lists
data[index]}
getItemCount={(data) => data.length}
renderItem={({ item }) => }
/>
```
## Integration with Other Modules
### With Wallet Providers
```typescript
import { useWallet } from '@/modules/wallet-providers';
import { useFetchTokens } from '@/modules/data-module';
function ConnectedTokenList() {
const { wallet } = useWallet();
const { tokens } = useFetchTokens(wallet?.address);
return ;
}
```
### With Swap Module
```typescript
import { useSwap } from '@/modules/swap';
import { useTokenSearch } from '@/modules/data-module';
function TokenSwapInterface() {
const { executeSwap } = useSwap();
const { tokens, setSearchQuery } = useTokenSearch();
return (
);
}
```
## Troubleshooting
**API Key Issues**
* Ensure all required API keys are set in environment variables
* Check API key permissions and rate limits
**Network Timeouts**
* The module includes retry logic, but network issues may still occur
* Implement proper loading states and error boundaries
**Token Not Found**
* Some tokens may not be available in all data sources
* Implement fallback mechanisms when token data is unavailable
## API Reference
For detailed API documentation, see:
* [Token Service Reference](/docs/references/modules/data-module/services)
* [Hooks Reference](/docs/references/modules/data-module/hooks)
* [Types Reference](/docs/references/modules/data-module/types)
***
The Data Module serves as the foundation for all blockchain data needs in your Solana application, providing reliable, cached, and efficiently formatted data from multiple sources.
# Mercuryo Module
Source: https://docs.solanaappkit.com/docs/modules/mercuryo
Fiat-to-crypto on-ramp and crypto-to-fiat off-ramp functionality through Mercuryo's payment gateway, offering seamless crypto purchases with multiple payment methods.
## Overview
The Mercuryo module integrates with Mercuryo's payment infrastructure to provide fiat gateway functionality. It enables seamless conversion between fiat currencies and cryptocurrencies through an intuitive interface with real-time exchange rates.
* Fiat to crypto conversion
* Multiple currencies (USD, EUR, GBP)
* Real-time rates & transparent fees
* Instant & bank transfer options
* Crypto to fiat conversion
* Fast settlement times
* Competitive exchange rates
* Multiple withdrawal options
* Credit/Debit Cards (Visa, Mastercard, Amex)
* Apple Pay (iOS)
* Bank transfers
* 3D Secure authentication
* Tab-based interface
* Real-time calculations
* Platform-optimized design
* Transaction summaries
## Module Structure
```
src/modules/mercuryo/
├── index.ts # Main exports
├── screens/
│ └── MercuryoScreen.tsx # Main Mercuryo interface
└── README.md # Documentation
```
## Payment Methods & Fees
| Method | Platforms | Fee | Processing Time |
| --------------------- | ------------ | ---- | ----------------- |
| **Credit/Debit Card** | iOS, Android | 2.5% | Instant |
| **Apple Pay** | iOS only | 1.8% | Instant |
| **Bank Transfer** | iOS, Android | 1.0% | 1-3 business days |
```typescript
const filteredPaymentMethods = paymentMethods.filter(method =>
!(method.appleOnly && Platform.OS !== 'ios')
);
```
## Supported Assets
| Currency | Symbol | Region |
| -------- | ------ | ---------------------- |
| **USD** | \$ | United States Dollar |
| **EUR** | € | Euro |
| **GBP** | £ | British Pound Sterling |
| Token | Symbol | Description |
| -------- | ------ | ------------------- |
| **SOL** | SOL | Native Solana token |
| **USDC** | USDC | USD Coin on Solana |
| **BONK** | BONK | Solana meme token |
## Transaction Flow
### On-Ramp (Buy)
Input desired fiat amount for purchase
Choose fiat and crypto currencies
Select preferred payment option
Confirm transaction details and complete payment
### Off-Ramp (Sell)
Input crypto amount to sell
Choose crypto and fiat currencies
Enter withdrawal bank information
Review and confirm withdrawal
## Usage Examples
```typescript Basic Integration
import { MercuroScreen } from '@/modules/mercuryo';
function App() {
return (
);
}
```
```typescript Navigation
const navigation = useNavigation();
const openMercuryo = () => {
navigation.navigate('Mercuryo');
};
```
```typescript Custom Assets
const cryptos = [
{ code: 'SOL', name: 'Solana', logo: require('./assets/sol.png') },
{ code: 'USDC', name: 'USD Coin', logo: require('./assets/usdc.png') },
];
```
## Configuration
### Environment Variables
```bash
MERCURYO_API_KEY=your_mercuryo_api_key
MERCURYO_ENVIRONMENT=sandbox # or production
MERCURYO_WIDGET_ID=your_widget_id
```
Never commit your actual API keys to version control. Use environment variables or secure key management.
## Key Features
On-ramp and off-ramp functionality for complete fiat-crypto conversion
Support for cards, Apple Pay, and bank transfers with platform-specific optimizations
Live exchange calculations and transparent fee structure
3D Secure authentication and KYC/AML compliance built-in
## Best Practices
**Implementation Tips:**
* Test thoroughly in sandbox environment
* Handle platform-specific payment methods appropriately
* Implement proper error handling for network issues
* Display clear fee breakdowns
* Cache exchange rates for better UX
***
Built with ❤️ for seamless fiat-crypto conversions - Powered by Mercuryo
# Meteora Module
Source: https://docs.solanaappkit.com/docs/modules/meteora
Dynamic Liquidity Markets (DLMM) integration with token creation, swapping, and liquidity management
The Meteora module integrates Meteora's Dynamic Liquidity Markets (DLMM) and advanced token creation functionalities. It provides sophisticated tools for token swapping, liquidity management, and creating tokens with customizable bonding curves.
## Core Functionalities
Execute efficient swaps using Meteora's advanced liquidity pools with optimal price discovery
Add, view, and manage liquidity positions in Meteora pools with real-time analytics
Create SPL or Token-2022 tokens with dynamic bonding curves and customizable parameters
Real-time visualization of token price curves based on creation parameters
## Installation & Setup
Ensure your backend server is running and accessible:
```bash
SERVER_URL=http://localhost:8080/api
```
Configure Meteora-specific settings in `.env.local`:
```bash
SERVER_URL=your_meteora_backend_url
METEORA_PROGRAM_ID=your_program_id
```
Import components and services:
```typescript
import {
MeteoraScreen,
TokenCreationForm,
meteoraService
} from '@/modules/meteora';
```
**Backend Dependency**: This module requires a backend service that implements the Meteora SDK for blockchain interactions.
## Module Architecture
```
src/modules/meteora/
├── components/ # UI components for Meteora features
├── screens/ # Top-level screen components
├── services/ # Backend API integration
├── types/ # TypeScript definitions
└── index.ts # Public API exports
```
## Core Components
**`TokenCreationForm`** - Multi-step token creation wizard
```typescript
import { TokenCreationForm } from '@/modules/meteora';
function CreateTokenScreen() {
const handleTokenCreated = (tokenData) => {
console.log('Token created:', tokenData);
// Handle success (navigation, notifications, etc.)
};
return (
navigation.goBack()}
/>
);
}
```
**Features:**
* Basic token information (name, symbol, description, image)
* Bonding curve parameters configuration
* Optional immediate token purchase
* Advanced fee settings
* Metadata upload to IPFS
**`SwapForm`** - Token swapping interface
```typescript
import { SwapForm } from '@/modules/meteora';
function MeteoraBased() {
const handleSwapComplete = (result) => {
console.log('Swap completed:', result);
};
return (
);
}
```
**Features:**
* Token selection with search
* Real-time quote updates
* Slippage configuration
* Transaction execution
**`LiquidityPanel`** - Liquidity position management
```typescript
import { LiquidityPanel } from '@/modules/meteora';
function LiquidityManagement() {
const handleLiquidityAdded = (position) => {
console.log('Liquidity added:', position);
};
return (
);
}
```
**Features:**
* View current positions
* Add new liquidity
* Position analytics
* Pool discovery
**`BondingCurveVisualizer`** - Dynamic price curve charts
```typescript
import { BondingCurveVisualizer } from '@/modules/meteora';
function CurvePreview({ tokenParams }) {
return (
);
}
```
**Features:**
* Real-time curve updates
* Interactive price points
* Market cap visualization
* Supply distribution
## Meteora Services
The `meteoraService.ts` provides a complete API client for Meteora backend operations:
```typescript
import { meteoraService } from '@/modules/meteora';
// Create token configuration
const config = await meteoraService.createConfig(
configParams,
connection,
wallet,
onStatusUpdate
);
// Build bonding curve by market cap
const curve = await meteoraService.buildCurveByMarketCap(
curveParams,
connection,
wallet,
onStatusUpdate
);
// Complete token creation with curve
const token = await meteoraService.createTokenWithCurve(
tokenParams,
connection,
wallet,
onStatusUpdate
);
```
**Available Functions:**
* `createConfig()` - Create DBC configuration
* `buildCurveByMarketCap()` - Build bonding curve
* `createPool()` - Create liquidity pool
* `uploadTokenMetadata()` - Upload to IPFS
* `createTokenWithCurve()` - Complete token launch
* `createPoolAndBuy()` - Create pool + initial purchase
```typescript
// Get swap quote
const quote = await meteoraService.fetchSwapQuote(
inputToken,
outputToken,
amount,
slippage,
poolAddress
);
// Execute trade
const result = await meteoraService.executeTrade(
tradeParams,
poolAddress,
wallet,
onStatusUpdate
);
```
**Available Functions:**
* `fetchSwapQuote()` - Get trading quotes
* `executeTrade()` - Execute swaps
* `fetchMeteoraPools()` - Get available pools
```typescript
// Fetch user positions
const positions = await meteoraService.fetchUserLiquidityPositions(
walletAddress
);
// Add liquidity
const result = await meteoraService.addLiquidity(
poolAddress,
tokenAAmount,
tokenBAmount,
slippage,
connection,
wallet,
onStatusUpdate
);
// Remove liquidity
const removal = await meteoraService.removeLiquidity(
positionId,
percentage,
connection,
wallet,
onStatusUpdate
);
```
**Available Functions:**
* `fetchUserLiquidityPositions()` - Get user positions
* `addLiquidity()` - Add to pools
* `removeLiquidity()` - Remove from pools
## Quick Start Example
```typescript Complete Token Creation
import { meteoraService } from '@/modules/meteora';
import { useWallet, useConnection } from '@/modules/wallet-providers';
function CreateMeteoraBased() {
const { wallet } = useWallet();
const { connection } = useConnection();
const [creating, setCreating] = useState(false);
const handleCreateToken = async () => {
setCreating(true);
try {
// Step 1: Upload metadata
const metadata = await meteoraService.uploadTokenMetadata({
name: 'My Token',
symbol: 'MTK',
description: 'A token created with Meteora',
image: imageFile
});
// Step 2: Create token with bonding curve
const result = await meteoraService.createTokenWithCurve(
{
tokenName: 'My Token',
tokenSymbol: 'MTK',
tokenDecimals: 9,
totalSupply: 1000000,
initialMarketCap: 10000,
migrationMarketCap: 100000,
metadataUri: metadata.uri
},
connection,
wallet,
(status) => console.log('Status:', status)
);
console.log('Token created successfully:', result);
} catch (error) {
console.error('Token creation failed:', error);
} finally {
setCreating(false);
}
};
return (
);
}
```
```typescript Token Swapping
import { SwapForm } from '@/modules/meteora';
function MeteoraTradingInterface() {
const [selectedPool, setSelectedPool] = useState(null);
const [pools, setPools] = useState([]);
useEffect(() => {
loadPools();
}, []);
const loadPools = async () => {
try {
const availablePools = await meteoraService.fetchMeteoraPools();
setPools(availablePools);
} catch (error) {
console.error('Failed to load pools:', error);
}
};
const handleSwapComplete = (result) => {
console.log('Swap completed:', result);
// Update UI, show success message, etc.
};
return (
Meteora Swap
);
}
```
```typescript Liquidity Management
import { LiquidityPanel } from '@/modules/meteora';
import { useWallet } from '@/modules/wallet-providers';
function LiquidityDashboard() {
const { wallet } = useWallet();
const [positions, setPositions] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (wallet?.address) {
loadLiquidityPositions();
}
}, [wallet?.address]);
const loadLiquidityPositions = async () => {
try {
const userPositions = await meteoraService.fetchUserLiquidityPositions(
wallet.address
);
setPositions(userPositions);
} catch (error) {
console.error('Failed to load positions:', error);
} finally {
setLoading(false);
}
};
const handleLiquidityAdded = (newPosition) => {
setPositions(prev => [...prev, newPosition]);
};
return (
Your Liquidity Positions
{loading ? (
) : (
)}
);
}
```
## TypeScript Definitions
The module provides comprehensive type definitions for all Meteora operations:
```typescript
// Core types
interface MeteoraTrade {
inputToken: string;
outputToken: string;
amount: number;
slippage: number;
poolAddress?: string;
}
interface LiquidityPosition {
id: string;
poolAddress: string;
tokenA: string;
tokenB: string;
amountA: number;
amountB: number;
share: number;
}
interface CreateConfigParams {
tokenName: string;
tokenSymbol: string;
tokenDecimals: number;
totalSupply: number;
initialMarketCap: number;
migrationMarketCap: number;
metadataUri?: string;
}
// Enums
enum TokenType {
SPL = 'spl',
TOKEN_2022 = 'token2022'
}
enum FeeSchedulerMode {
FIXED = 'fixed',
DYNAMIC = 'dynamic'
}
```
## Advanced Features
### Custom Bonding Curves
Create bonding curves based on target market capitalizations:
```typescript
const curveParams = {
initialMarketCap: 50000, // Starting market cap
migrationMarketCap: 500000, // Target for migration
totalSupply: 1000000, // Total token supply
curveSteepness: 2.5, // Curve aggressiveness
};
const curve = await meteoraService.buildCurveByMarketCap(
curveParams,
connection,
wallet,
statusCallback
);
```
Fine-tune bonding curve behavior:
```typescript
const advancedParams = {
activationType: ActivationType.TIMESTAMP,
migrationOption: MigrationOption.BURN_LP,
feeSchedulerMode: FeeSchedulerMode.DYNAMIC,
collectFeeMode: CollectFeeMode.PROTOCOL_FEE,
lpDistribution: {
creator: 0.7, // 70% to creator
protocol: 0.2, // 20% to protocol
community: 0.1 // 10% to community
}
};
```
### Real-time Monitoring
```typescript
function useMeteoraBased(tokenAddress) {
const [priceData, setPriceData] = useState(null);
const [liquidityData, setLiquidityData] = useState(null);
useEffect(() => {
const interval = setInterval(async () => {
try {
// Fetch real-time price data
const price = await meteoraService.fetchTokenPrice(tokenAddress);
setPriceData(price);
// Fetch liquidity data
const liquidity = await meteoraService.fetchPoolLiquidity(tokenAddress);
setLiquidityData(liquidity);
} catch (error) {
console.error('Failed to fetch real-time data:', error);
}
}, 10000); // Update every 10 seconds
return () => clearInterval(interval);
}, [tokenAddress]);
return { priceData, liquidityData };
}
```
## Integration Patterns
### With Other Modules
Seamless transaction signing and wallet management
Real-time price feeds and market data
Social trading and token launch announcements
Token-gated NFT access and rewards
### Combined Usage Example
```typescript
import { useWallet } from '@/modules/wallet-providers';
import { useFetchTokens } from '@/modules/data-module';
import { useThread } from '@/core/thread';
import { meteoraService } from '@/modules/meteora';
function IntegratedTokenLaunch() {
const { wallet } = useWallet();
const { refetch: refetchTokens } = useFetchTokens(wallet?.address);
const { createPost } = useThread();
const handleTokenLaunch = async (tokenData) => {
try {
// Create token with Meteora
const result = await meteoraService.createTokenWithCurve(
tokenData,
connection,
wallet,
statusUpdate
);
// Refresh user's token list
await refetchTokens();
// Create social post about the launch
await createPost({
content: `🚀 Just launched ${tokenData.tokenName} with Meteora DLMM!`,
type: 'token_launch',
attachments: [result.tokenAddress]
});
console.log('Token launched and announced:', result);
} catch (error) {
console.error('Token launch failed:', error);
}
};
return ;
}
```
## Error Handling & Status Updates
```typescript
function MeteoraBased() {
const [status, setStatus] = useState('');
const [error, setError] = useState(null);
const handleStatusUpdate = (update) => {
setStatus(update.message);
if (update.error) {
setError(update.error);
}
if (update.completed) {
setStatus('Transaction completed successfully!');
setTimeout(() => setStatus(''), 3000);
}
};
const createToken = async () => {
setError(null);
try {
await meteoraService.createTokenWithCurve(
tokenParams,
connection,
wallet,
handleStatusUpdate
);
} catch (error) {
setError(error.message);
console.error('Meteora operation failed:', error);
}
};
return (
{status && {status}}
{error && {error}}
);
}
```
## Troubleshooting
**Backend Connection Issues**
* Verify `SERVER_URL` is correctly configured
* Ensure backend service is running and accessible
* Check network connectivity and firewall settings
**Transaction Failures**
* Insufficient SOL for transaction fees
* Wallet connection issues
* Network congestion or RPC rate limits
**Bonding Curve Configuration**
* Invalid market cap ratios (migration must be > initial)
* Supply parameters don't match curve expectations
* Fee configurations exceed maximum allowed values
## Performance Considerations
**Batch Operations**: When possible, batch multiple operations to reduce transaction costs and improve user experience.
**Gas Optimization**: Meteora operations can be gas-intensive. Always provide clear fee estimates to users.
## API Reference
For detailed API documentation, see:
* [Meteora Service Reference](/docs/references/modules/meteora/services)
* [Components Reference](/docs/references/modules/meteora/components)
* [Types Reference](/docs/references/modules/meteora/types)
***
The Meteora module provides advanced DeFi capabilities with professional-grade bonding curves and liquidity management, perfect for sophisticated token economics and trading strategies.
# MoonPay Module
Source: https://docs.solanaappkit.com/docs/modules/moonpay
Seamless fiat on-ramp integration for purchasing cryptocurrency with credit cards and Apple Pay
The MoonPay module provides seamless cryptocurrency purchasing capabilities directly within your app. Users can buy crypto using credit cards, debit cards, Apple Pay, and other payment methods through MoonPay's trusted platform.
## Core Functionalities
Purchase cryptocurrencies directly using various payment methods with automatic wallet integration
Automatically populates the user's connected wallet address as the destination for purchases
Configurable MoonPay widget supporting both sandbox and production environments
View wallet balances and seamlessly navigate to purchase flows when funds are needed
## Installation & Setup
The module uses the official MoonPay React Native SDK:
```bash
npm install @moonpay/react-native-moonpay-sdk
```
Add your MoonPay API key to `.env.local`:
```bash
MOONPAY_API_KEY=pk_test_your_api_key_here
# For production: pk_live_your_production_key
```
Import the components you need:
```typescript
import {
MoonPayWidget,
OnrampScreen,
WalletScreen
} from '@/modules/moonpay';
```
**API Keys**: Use `pk_test_` prefixed keys for testing and `pk_live_` for production. The module automatically detects the environment.
## Module Architecture
```
src/modules/moonpay/
├── components/ # UI components
│ └── MoonPayWidget/ # Core MoonPay WebView wrapper
├── screens/ # Complete screen implementations
├── services/ # MoonPay configuration and utilities
├── types/ # TypeScript definitions
└── utils/ # Helper functions
```
## Core Components
**`MoonPayWidget`** - Core component that embeds MoonPay's purchase flow
```typescript
import { MoonPayWidget } from '@/modules/moonpay';
function PurchaseCrypto() {
const handleWidgetOpen = () => {
console.log('MoonPay widget opened');
};
const handleError = (error) => {
console.error('MoonPay error:', error);
};
return (
console.log('Retrying...')}
/>
);
}
```
**Props:**
* `apiKey` - Your MoonPay API key
* `environment` - 'sandbox' or 'production'
* `height` - Widget height in pixels
* `onOpen` - Callback when widget loads
* `onError` - Error handling callback
* `onRetry` - Retry mechanism callback
**`OnrampScreen`** - Complete purchase screen with navigation and wallet integration
```typescript
import { OnrampScreen } from '@/modules/moonpay';
function AppNavigator() {
return (
);
}
```
**Features:**
* Automatic wallet address detection
* Loading and error states
* Navigation header integration
* Informational content about the purchase process
**`WalletScreen`** - Wallet balance display with on-ramp entry point
```typescript
import { WalletScreen } from '@/modules/moonpay';
import { useNavigation } from '@react-navigation/native';
function WalletTab() {
const navigation = useNavigation();
return (
navigation.navigate('OnrampScreen')}
showBalance={true}
showAddFundsButton={true}
/>
);
}
```
**Features:**
* SOL balance display
* Wallet address with copy functionality
* Add funds button integration
* Balance refresh capability
## Quick Start Example
```typescript Basic Integration
import { OnrampScreen } from '@/modules/moonpay';
import { useWallet } from '@/modules/wallet-providers';
function BuyCryptoFlow() {
const { wallet } = useWallet();
if (!wallet) {
return (
Please connect your wallet first
);
}
return (
Buy Cryptocurrency
Funds will be sent to: {wallet.address}
);
}
```
```typescript Custom Widget Implementation
import { MoonPayWidget } from '@/modules/moonpay';
import { useWallet } from '@/modules/wallet-providers';
import { useState } from 'react';
function CustomPurchaseScreen() {
const { wallet } = useWallet();
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const handleWidgetLoad = () => {
setLoading(false);
console.log('MoonPay widget loaded successfully');
};
const handleWidgetError = (err) => {
setLoading(false);
setError(err.message);
console.error('MoonPay error:', err);
};
const handleRetry = () => {
setError(null);
setLoading(true);
};
return (
Purchase Crypto
Destination: {formatWalletAddress(wallet?.address)}
{loading && (
Loading MoonPay...
)}
{error && (
{error}
)}
);
}
```
```typescript Navigation Integration
import { useNavigation } from '@react-navigation/native';
import { WalletScreen } from '@/modules/moonpay';
function MainWalletTab() {
const navigation = useNavigation();
const handleAddFunds = () => {
navigation.navigate('OnrampScreen');
};
const handleViewTransactions = () => {
navigation.navigate('TransactionHistory');
};
return (
navigation.navigate('SwapScreen')
}
]}
/>
);
}
```
## MoonPay Service Configuration
The `moonpayService.ts` provides configuration and validation utilities:
```typescript
import { createMoonPayService } from '@/modules/moonpay';
// Create MoonPay service instance
const moonPayService = createMoonPayService({
apiKey: process.env.MOONPAY_API_KEY,
environment: 'sandbox', // or 'production'
});
// Validate configuration
const isValid = moonPayService.validateConfig();
if (!isValid) {
console.error('MoonPay configuration is invalid');
}
// Get widget URL (if needed for custom implementations)
const widgetUrl = moonPayService.getWidgetUrl({
walletAddress: userWallet.address,
currencyCode: 'SOL',
baseCurrencyCode: 'USD',
});
```
## Utility Functions
**`formatWalletAddress(address)`** - Shortens wallet addresses for display
```typescript
import { formatWalletAddress } from '@/modules/moonpay/utils';
const address = '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM';
const formatted = formatWalletAddress(address);
// Returns: "9WzD...AWWM"
```
**`parseErrorMessage(error)`** - Converts raw errors to user-friendly messages
```typescript
import { parseErrorMessage } from '@/modules/moonpay/utils';
try {
// MoonPay operation
} catch (error) {
const userMessage = parseErrorMessage(error);
Alert.alert('Purchase Failed', userMessage);
}
```
**`getEnvironmentFromConfig(apiKey)`** - Automatically detects sandbox vs production
```typescript
import { getEnvironmentFromConfig } from '@/modules/moonpay/utils';
const environment = getEnvironmentFromConfig(process.env.MOONPAY_API_KEY);
// Returns: 'sandbox' for pk_test_ keys, 'production' for pk_live_ keys
```
## Advanced Usage Patterns
### Custom Purchase Flow
```typescript
function CustomPurchaseFlow() {
const { wallet } = useWallet();
const [purchaseAmount, setPurchaseAmount] = useState('');
const [selectedCurrency, setSelectedCurrency] = useState('SOL');
const initiateCustomPurchase = () => {
// Custom logic before showing MoonPay widget
analytics.track('purchase_initiated', {
amount: purchaseAmount,
currency: selectedCurrency,
wallet: wallet.address
});
// Show MoonPay widget with pre-filled values
navigation.navigate('OnrampScreen', {
defaultAmount: purchaseAmount,
defaultCurrency: selectedCurrency
});
};
return (
);
}
```
### Transaction Status Tracking
```typescript
function useMoonPayTransactionStatus() {
const [transactions, setTransactions] = useState([]);
const [loading, setLoading] = useState(false);
const trackTransaction = async (transactionId) => {
setLoading(true);
try {
// Note: This would require backend integration with MoonPay's API
const status = await fetch(`/api/moonpay/transaction/${transactionId}`);
const data = await status.json();
setTransactions(prev =>
prev.map(tx =>
tx.id === transactionId
? { ...tx, status: data.status }
: tx
)
);
} catch (error) {
console.error('Failed to track transaction:', error);
} finally {
setLoading(false);
}
};
return { transactions, trackTransaction, loading };
}
```
### Balance-Based Recommendations
```typescript
function BalanceBasedOnramp() {
const { wallet } = useWallet();
const { balance } = useBalance(wallet?.address);
const [showRecommendation, setShowRecommendation] = useState(false);
useEffect(() => {
// Show purchase recommendation if balance is low
if (balance < 0.1) { // Less than 0.1 SOL
setShowRecommendation(true);
}
}, [balance]);
if (!showRecommendation) return null;
return (
Low Balance Detected
Your SOL balance is low ({balance.toFixed(4)} SOL).
Consider adding funds to cover transaction fees.
);
}
```
## Integration with Other Modules
Automatic wallet address detection and integration
Real-time balance updates and transaction history
Purchase crypto then immediately swap to desired tokens
Share purchase milestones and achievements
### Combined Workflow Example
```typescript
import { useWallet } from '@/modules/wallet-providers';
import { useFetchTokens } from '@/modules/data-module';
import { useSwap } from '@/modules/swap';
import { MoonPayWidget } from '@/modules/moonpay';
function BuyAndSwapFlow() {
const { wallet } = useWallet();
const { refetch: refetchBalance } = useFetchTokens(wallet?.address);
const { executeSwap } = useSwap();
const [purchaseComplete, setPurchaseComplete] = useState(false);
const handlePurchaseComplete = async () => {
setPurchaseComplete(true);
// Refresh balance after purchase
await refetchBalance();
// Optional: Auto-swap purchased SOL to another token
const shouldSwap = await askUserForSwap();
if (shouldSwap) {
navigation.navigate('SwapScreen', {
inputToken: 'SOL',
outputToken: 'USDC'
});
}
};
return (
{!purchaseComplete ? (
) : (
navigation.goBack()} />
)}
);
}
```
## Environment Configuration
```bash
# .env.local for development
MOONPAY_API_KEY=pk_test_your_sandbox_key_here
```
* Uses sandbox environment automatically
* Test transactions don't involve real money
* Full widget functionality for testing
```bash
# .env.local for production
MOONPAY_API_KEY=pk_live_your_production_key_here
```
* Uses live MoonPay environment
* Real transactions with actual payment processing
* Requires KYC compliance and full verification
## Error Handling & Troubleshooting
**Widget Not Loading**
* Verify `MOONPAY_API_KEY` is correctly set
* Check internet connectivity
* Ensure API key has proper permissions
**Payment Failures**
* Card verification issues
* Insufficient funds
* Geographic restrictions
* KYC requirements not met
**Network Errors**
* Backend connectivity issues
* Solana network congestion
* Invalid wallet addresses
```typescript
function RobustMoonPayWidget() {
const [error, setError] = useState(null);
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 3;
const handleError = (err) => {
console.error('MoonPay error:', err);
setError(parseErrorMessage(err));
};
const handleRetry = () => {
if (retryCount < maxRetries) {
setRetryCount(prev => prev + 1);
setError(null);
} else {
Alert.alert(
'Connection Failed',
'Please check your internet connection and try again later.'
);
}
};
return (
{error ? (
) : (
)}
);
}
```
## Security Considerations
**API Key Security**: Never expose production API keys in client-side code. Consider using a backend proxy for additional security.
**User Verification**: MoonPay handles KYC/AML compliance, but ensure your app provides clear information about verification requirements.
## API Reference
For detailed API documentation, see:
* [MoonPay Components Reference](/docs/references/modules/moonpay/components)
* [Services Reference](/docs/references/modules/moonpay/services)
* [Types Reference](/docs/references/modules/moonpay/types)
***
The MoonPay module provides a seamless bridge between traditional finance and crypto, enabling users to easily onboard into the Solana ecosystem with familiar payment methods.
# NFT Module
Source: https://docs.solanaappkit.com/docs/modules/nft
Complete NFT functionality for buying, selling, and managing digital collectibles with Tensor integration
The NFT module provides comprehensive functionality for interacting with Non-Fungible Tokens (NFTs) on the Solana blockchain. It integrates with the Tensor API for fetching NFT data, collection information, and performing buy/sell operations.
## Core Functionalities
View and manage all NFTs owned by a user with detailed metadata and pricing information
Search and browse NFT collections with floor price tracking and collection analytics
Purchase individual NFTs or floor NFTs from collections with integrated Tensor trading
List owned NFTs for sale with custom pricing and duration settings
## Installation & Setup
Configure your Tensor API access in `.env.local`:
```bash
TENSOR_API_KEY=your_tensor_api_key_here
HELIUS_API_KEY=your_helius_api_key_here # Optional for compressed NFTs
```
Import the components and hooks you need:
```typescript
import {
NftScreen,
useFetchNFTs,
NftDetailsSection,
nftService
} from '@/modules/nft';
```
Ensure wallet providers are configured for transaction signing:
```typescript
import { useWallet } from '@/modules/wallet-providers';
```
**Tensor API**: This module primarily uses Tensor's API for NFT data and trading. Ensure you have appropriate API access and rate limits configured.
## Module Architecture
```
src/modules/nft/
├── components/ # Reusable NFT UI components
├── hooks/ # Custom React hooks for NFT data
├── screens/ # Complete NFT trading screens
├── services/ # Tensor API integration
├── types/ # TypeScript definitions
└── utils/ # NFT-specific utilities
```
## Core Components
**`NftScreen`** - Main NFT trading interface with buy/sell tabs
```typescript
import { NftScreen } from '@/modules/nft';
function NFTMarketplace() {
return (
);
}
```
**Features:**
* Tabbed interface for buying and selling
* Collection search and discovery
* User's NFT portfolio display
* Integrated trading functionality
**`BuySection`** - NFT discovery and purchase interface
```typescript
import { BuySection } from '@/modules/nft';
function NFTBuyInterface() {
const handlePurchaseComplete = (nft) => {
console.log('NFT purchased:', nft);
// Handle success (refresh portfolio, show confirmation, etc.)
};
return (
);
}
```
**Features:**
* Collection search by name
* Floor NFT discovery
* Price comparison tools
* One-click floor purchases
**`SellSection`** - NFT listing and management interface
```typescript
import { SellSection } from '@/modules/nft';
import { useWallet } from '@/modules/wallet-providers';
function NFTSellInterface() {
const { wallet } = useWallet();
const handleListingCreated = (listing) => {
console.log('NFT listed:', listing);
};
return (
);
}
```
**Features:**
* User's NFT portfolio display
* Custom listing creation
* Active listing management
* Price and duration controls
**`NftDetailsSection`** - Detailed NFT information display
```typescript
import { NftDetailsSection } from '@/modules/nft';
function NFTDetailModal({ nftMint, visible }) {
return (
);
}
```
**Features:**
* Comprehensive metadata display
* Image rendering with fallbacks
* Price history and analytics
* Social sharing capabilities
## Core Hook: useFetchNFTs
The primary hook for fetching user's NFT portfolio:
```typescript
import { useFetchNFTs } from '@/modules/nft';
import { useWallet } from '@/modules/wallet-providers';
function UserNFTPortfolio() {
const { wallet } = useWallet();
const { nfts, loading, error, refetch } = useFetchNFTs(wallet?.address, {
includeCompressed: true,
includeMetadata: true,
sortBy: 'floorPrice'
});
if (loading) return ;
if (error) return ;
return (
Your NFTs ({nfts.length}) item.mint}
renderItem={({ item }) => (
openNFTDetails(item)}
/>
)}
onRefresh={refetch}
refreshing={loading}
/>
);
}
```
**Hook Parameters:**
* `walletAddress` - User's wallet address
* `options` - Configuration object with:
* `includeCompressed` - Include compressed NFTs
* `includeMetadata` - Fetch full metadata
* `sortBy` - Sort order preference
**Returns:**
* `nfts` - Array of NFT items
* `loading` - Loading state
* `error` - Error message if any
* `refetch` - Function to refresh data
## NFT Service Functions
The `nftService.ts` provides comprehensive Tensor API integration:
```typescript
import { nftService } from '@/modules/nft';
// Fetch NFT metadata
const nftData = await nftService.fetchNftMetadata(mintAddress);
// Fetch collection information
const collection = await nftService.fetchCollectionData(collectionId);
// Get floor NFT for collection
const floorNFT = await nftService.fetchFloorNFTForCollection(collectionId);
// Search collections
const results = await nftService.searchCollections('Okay Bears');
// Fetch active listings for user
const listings = await nftService.fetchActiveListings(walletAddress);
```
**Available Functions:**
* `fetchNftMetadata(mint)` - Get detailed NFT metadata
* `fetchCollectionData(collId)` - Collection information and stats
* `fetchFloorNFTForCollection(collId)` - Current floor NFT details
* `searchCollections(query)` - Search collections by name
* `fetchActiveListings(walletAddress)` - User's active listings
```typescript
// Buy a specific NFT
const buyResult = await nftService.buyNft(
userPublicKey,
nftMint,
maxPriceSol,
currentOwner,
sendTransaction,
(status) => console.log('Buy status:', status)
);
// Buy floor NFT from collection
const floorBuyResult = await nftService.buyCollectionFloor(
userPublicKey,
collectionId,
sendTransaction,
(status) => console.log('Floor buy status:', status)
);
// List NFT for sale
const listResult = await nftService.listNftForSale(
userPublicKey,
nftMint,
priceSol,
userWallet,
(status) => console.log('List status:', status),
isCompressed,
compressedNftData
);
// Delist NFT
const delistResult = await nftService.delistNft(
userPublicKey,
nftMint,
userWallet,
(status) => console.log('Delist status:', status)
);
```
**Transaction Functions:**
* `buyNft()` - Purchase specific NFT
* `buyCollectionFloor()` - Buy floor-priced NFT
* `listNftForSale()` - Create new listing
* `delistNft()` - Remove existing listing
## Quick Start Examples
```typescript Basic NFT Portfolio
import { useFetchNFTs, NftDetailsSection } from '@/modules/nft';
import { useWallet } from '@/modules/wallet-providers';
function MyNFTCollection() {
const { wallet } = useWallet();
const { nfts, loading, error } = useFetchNFTs(wallet?.address);
const [selectedNFT, setSelectedNFT] = useState(null);
if (!wallet) {
return ;
}
return (
My NFT Collection
{loading && }
{error && (
window.location.reload()}
/>
)}
item.mint}
renderItem={({ item }) => (
setSelectedNFT(item)}
>
{item.name}
{item.price ? `${item.price} SOL` : 'Not Listed'}
)}
/>
{selectedNFT && (
setSelectedNFT(null)}
/>
)}
);
}
```
```typescript NFT Marketplace Interface
import { NftScreen } from '@/modules/nft';
import { useWallet } from '@/modules/wallet-providers';
function NFTMarketplace() {
const { wallet, isAuthenticated } = useWallet();
const [activeTab, setActiveTab] = useState('buy');
const handleNFTPurchased = (nft) => {
Alert.alert(
'Purchase Successful!',
`You successfully purchased ${nft.name}`,
[{ text: 'OK', onPress: () => setActiveTab('sell') }]
);
};
const handleNFTListed = (listing) => {
Alert.alert(
'NFT Listed!',
`${listing.name} is now listed for ${listing.price} SOL`
);
};
if (!isAuthenticated) {
return (
Connect Your Wallet
Connect your wallet to browse and trade NFTs
);
}
return (
NFT Marketplace
);
}
```
```typescript Custom NFT Trading
import { nftService } from '@/modules/nft';
import { useWallet } from '@/modules/wallet-providers';
function CustomNFTTrading() {
const { wallet, sendTransaction } = useWallet();
const [selectedCollection, setSelectedCollection] = useState(null);
const [floorNFT, setFloorNFT] = useState(null);
const [buying, setBuying] = useState(false);
const searchCollections = async (query) => {
try {
const results = await nftService.searchCollections(query);
return results;
} catch (error) {
console.error('Search failed:', error);
return [];
}
};
const loadFloorNFT = async (collectionId) => {
try {
const floor = await nftService.fetchFloorNFTForCollection(collectionId);
setFloorNFT(floor);
} catch (error) {
console.error('Failed to load floor NFT:', error);
}
};
const buyFloorNFT = async () => {
if (!floorNFT || !wallet) return;
setBuying(true);
try {
const result = await nftService.buyCollectionFloor(
wallet.publicKey,
selectedCollection.id,
sendTransaction,
(status) => console.log('Purchase status:', status)
);
Alert.alert('Success!', 'NFT purchased successfully');
} catch (error) {
Alert.alert('Purchase Failed', error.message);
} finally {
setBuying(false);
}
};
return (
Quick Floor Purchases {
setSelectedCollection(collection);
loadFloorNFT(collection.id);
}}
/>
{floorNFT && (
{floorNFT.name}{floorNFT.price} SOL
)}
);
}
```
## NFT Utilities
The module includes specialized utilities for handling NFT data:
**`imageUtils.ts`** - NFT image handling and formatting
```typescript
import { fixImageUrl, getNftImageSource, formatSolPrice } from '@/modules/nft/utils';
// Fix various image URL formats (IPFS, Arweave, etc.)
const imageUrl = fixImageUrl('ipfs://QmYourImageHash');
// Returns: https://gateway.ipfs.io/ipfs/QmYourImageHash
// Get React Native image source
const imageSource = getNftImageSource(nft.image, defaultImage);
// Format SOL prices consistently
const formattedPrice = formatSolPrice(1500000000, true); // true = lamports
// Returns: "1.5 SOL"
```
## Advanced Features
### NFT Sharing Integration
```typescript
import { NftListingModal } from '@/modules/nft';
import { useThread } from '@/core/thread';
function ShareNFTFeature() {
const { createPost } = useThread();
const [showNFTModal, setShowNFTModal] = useState(false);
const handleShareNFT = async (nftData) => {
try {
await createPost({
content: `Check out this amazing NFT! 🎨`,
type: 'nft_listing',
sections: [
{
type: 'nft_listing',
data: nftData
}
]
});
setShowNFTModal(false);
Alert.alert('Success', 'NFT shared to your feed!');
} catch (error) {
Alert.alert('Error', 'Failed to share NFT');
}
};
return (
);
}
```
### Real-time Floor Price Tracking
```typescript
function useFloorPriceTracking(collectionId) {
const [floorPrice, setFloorPrice] = useState(null);
const [priceChange, setPriceChange] = useState(0);
useEffect(() => {
if (!collectionId) return;
const trackFloorPrice = async () => {
try {
const floorNFT = await nftService.fetchFloorNFTForCollection(collectionId);
const newPrice = floorNFT.price;
if (floorPrice !== null) {
const change = ((newPrice - floorPrice) / floorPrice) * 100;
setPriceChange(change);
}
setFloorPrice(newPrice);
} catch (error) {
console.error('Floor price tracking error:', error);
}
};
// Initial load
trackFloorPrice();
// Update every 30 seconds
const interval = setInterval(trackFloorPrice, 30000);
return () => clearInterval(interval);
}, [collectionId, floorPrice]);
return { floorPrice, priceChange };
}
```
### Batch NFT Operations
```typescript
function useBatchNFTOperations() {
const { wallet, sendTransaction } = useWallet();
const batchListNFTs = async (nfts, pricePerNFT) => {
const results = [];
for (const nft of nfts) {
try {
const result = await nftService.listNftForSale(
wallet.publicKey,
nft.mint,
pricePerNFT,
wallet,
(status) => console.log(`${nft.name}: ${status}`)
);
results.push({ nft: nft.name, success: true, result });
} catch (error) {
results.push({ nft: nft.name, success: false, error: error.message });
}
}
return results;
};
const batchBuyFloorNFTs = async (collectionIds) => {
const results = [];
for (const collectionId of collectionIds) {
try {
const result = await nftService.buyCollectionFloor(
wallet.publicKey,
collectionId,
sendTransaction,
(status) => console.log(`Collection ${collectionId}: ${status}`)
);
results.push({ collection: collectionId, success: true, result });
} catch (error) {
results.push({ collection: collectionId, success: false, error: error.message });
}
}
return results;
};
return { batchListNFTs, batchBuyFloorNFTs };
}
```
## Integration with Other Modules
Transaction signing and wallet address management for NFT operations
Enhanced NFT metadata and portfolio value calculations
Social sharing of NFT listings and collection discoveries
Purchase SOL to fund NFT acquisitions
## Error Handling & Troubleshooting
**NFT Images Not Loading**
* IPFS gateway timeouts or failures
* Malformed metadata URLs
* Network connectivity issues
**Transaction Failures**
* Insufficient SOL for transaction fees
* NFT no longer available (sold by someone else)
* Wallet connection issues
**API Rate Limits**
* Too many requests to Tensor API
* Missing or invalid API key
* Temporary service unavailability
```typescript
function RobustNFTOperation() {
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 3;
const safeNFTOperation = async (operation) => {
try {
return await operation();
} catch (error) {
if (retryCount < maxRetries && error.message.includes('rate limit')) {
setRetryCount(prev => prev + 1);
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, retryCount)));
return safeNFTOperation(operation);
}
throw error;
}
};
return { safeNFTOperation };
}
```
## Performance Considerations
**Image Optimization**: Use image caching and lazy loading for better performance when displaying large NFT collections.
**API Limits**: Be mindful of Tensor API rate limits, especially when fetching large collections or making frequent requests.
## API Reference
For detailed API documentation, see:
* [NFT Components Reference](/docs/references/modules/nft/components)
* [Services Reference](/docs/references/modules/nft/services)
* [Hooks Reference](/docs/references/modules/nft/hooks)
* [Types Reference](/docs/references/modules/nft/types)
***
The NFT module provides a complete digital collectibles trading platform, enabling users to discover, buy, sell, and manage NFTs with professional-grade tools and seamless Tensor integration.
# Modules Overview
Source: https://docs.solanaappkit.com/docs/modules/overview
Complete guide to all available modules in the Solana App Kit
The Solana App Kit is built with a modular architecture, allowing you to use only the features you need while maintaining clean separation of concerns. Each module encapsulates a specific protocol or functionality.
## Available Modules
Multi-provider wallet integration with Privy, Dynamic, Turnkey, and Mobile Wallet Adapter support
Token swapping via Jupiter aggregator with best price routing across all DEXs
Meme token creation, trading, and community features with Pump.fun integration
Advanced AMM and concentrated liquidity features via Raydium protocol
Dynamic liquidity pools and yield farming with Meteora protocol
Custom token creation with bonding curves, staking, and vesting features
NFT minting, trading, and display with Metaplex and Tensor integration
Blockchain data fetching, token prices, and market analytics
Fiat on-ramp integration for buying crypto with cards and Apple Pay
AI-powered Solana interactions and automated trading assistance
## Module Categories
### 🔐 Wallet & Authentication
* **[Embedded Wallets](/docs/modules/wallet-providers)**: Multi-provider wallet connection and management
### 💱 Trading & DeFi
* **[Swap](/docs/modules/swap)**: Token swapping and DEX aggregation
* **[Pump.fun](/docs/modules/pump-fun)**: Meme token ecosystem
* **[Raydium](/docs/modules/raydium)**: Advanced AMM features
* **[Meteora](/docs/modules/meteora)**: Dynamic liquidity protocols
* **[TokenMill](/docs/modules/token-mill)**: Custom token creation
### 🎨 Assets & Media
* **[NFT](/docs/modules/nft)**: Non-fungible token functionality
### 📊 Data & Analytics
* **[Data Module](/docs/modules/data-module)**: Blockchain data and analytics
### 💳 Payments
* **[MoonPay](/docs/modules/moonpay)**: Fiat payment processing
### 🤖 AI & Automation
* **[Solana Agent Kit](/docs/modules/solana-agent-kit)**: AI-powered interactions
## Module Architecture
Each module follows a consistent structure:
```
module-name/
├── components/ # React Native UI components
├── hooks/ # Custom React hooks
├── services/ # API and blockchain services
├── screens/ # Module-specific screens
├── types/ # TypeScript type definitions
├── utils/ # Utility functions
├── index.ts # Public API exports
└── README.md # Module documentation
```
## Integration Patterns
### Independent Usage
```typescript
// Use individual modules
import { useSwap } from '@/modules/swap';
import { useNFT } from '@/modules/nft';
function MyComponent() {
const { executeSwap } = useSwap();
const { mintNFT } = useNFT();
// Use module functionality
}
```
### Combined Functionality
```typescript
// Combine multiple modules
import { useWallet } from '@/modules/wallet-providers';
import { useSwap } from '@/modules/swap';
import { useThread } from '@/core/thread';
function TradingPost() {
const { wallet } = useWallet();
const { executeSwap } = useSwap();
const { createPost } = useThread();
// Create trading posts that execute swaps
}
```
### Module Dependencies
Most modules depend on:
* **Wallet Providers**: For transaction signing
* **Data Module**: For token information
Some modules can enhance others:
* **Thread + Trading**: Social trading posts
* **NFT + Swap**: NFT marketplace features
* **AI + Any Module**: Automated interactions
## Getting Started with Modules
Identify which protocols and features your app needs
Each module lists its specific dependencies and setup requirements
Set up API keys and environment variables for chosen modules
Import and configure modules in your app
## Module Comparison
| Module | Complexity | Setup Time | Key Use Cases |
| ---------------- | ---------- | ---------- | ---------------------------------------- |
| Wallet Providers | Medium | 15 min | User authentication, transaction signing |
| Swap | Low | 5 min | Token trading, price discovery |
| Pump.fun | Low | 10 min | Meme tokens, viral trading |
| Raydium | High | 30 min | Advanced DeFi, liquidity provision |
| Meteora | High | 30 min | Yield farming, dynamic pools |
| TokenMill | High | 45 min | Custom tokenomics, advanced features |
| NFT | Medium | 20 min | Digital collectibles, marketplace |
| Data Module | Low | 5 min | Market data, analytics |
| MoonPay | Medium | 20 min | Fiat payments, onboarding |
| Solana Agent Kit | Medium | 25 min | AI trading, automation |
## Best Practices
**Start Small**: Begin with 2-3 core modules and add others as needed
**Wallet First**: Always set up Embedded Wallets Module before other modules
**Environment Variables**: Each module requires specific API keys and configuration
## Module Roadmap
Future modules in development:
* **Governance**: DAO and voting functionality
* **Lending**: DeFi lending protocols
* **Options**: Derivatives trading
* **Social**: Enhanced social features
***
Ready to dive into a specific module? Choose from the cards above or explore the detailed documentation for each integration.
# Pumpfun Module
Source: https://docs.solanaappkit.com/docs/modules/pumpfun
Complete meme token ecosystem with token launching, trading, and automated market making via Pump.fun and PumpSwap
The Pump.fun module provides comprehensive integration with the Pump.fun platform and PumpSwap AMM, enabling users to launch meme tokens, trade on bonding curves, and participate in automated market making.
## Core Functionalities
Create and launch new tokens on Pump.fun with metadata upload, social links, and initial liquidity
Buy and sell tokens using Pump.fun's bonding curve mechanism with automatic Raydium migration
Full PumpSwap AMM integration with swapping, liquidity management, and pool creation
Automatic token verification submission to RugCheck for community safety
## Installation & Setup
Ensure your backend server is running for metadata uploads and PumpSwap SDK:
```bash
SERVER_URL=http://localhost:8080/api
```
Configure required environment variables in `.env.local`:
```bash
SERVER_URL=your_backend_server_url
HELIUS_STAKED_URL=your_helius_rpc_endpoint
COMMISSION_WALLET=your_commission_wallet_address
```
Import the components and services you need:
```typescript
import {
PumpfunLaunchSection,
PumpfunBuySection,
PumpSwapScreen,
usePumpFun
} from '@/modules/pump-fun';
```
**Backend Dependency**: This module requires a backend service for metadata uploads and PumpSwap SDK interactions. Ensure proper server configuration.
## Module Architecture
```
src/modules/pump-fun/
├── components/ # UI components for both platforms
│ ├── pump-swap/ # PumpSwap AMM specific components
│ ├── PumpfunBuySection.tsx
│ ├── PumpfunLaunchSection.tsx
│ └── PumpfunSellSection.tsx
├── hooks/ # React hooks for interactions
├── navigation/ # PumpSwap navigation setup
├── screens/ # Complete screen implementations
├── services/ # API integration and business logic
├── types/ # TypeScript definitions
└── utils/ # Helper functions and utilities
```
## Core Components
**`PumpfunLaunchSection`** - Complete token creation interface
```typescript
import { PumpfunLaunchSection } from '@/modules/pump-fun';
function TokenLaunchScreen() {
const handleTokenLaunched = (tokenData) => {
console.log('Token launched:', tokenData);
// Handle success (navigation, notifications, etc.)
};
return (
);
}
```
**Features:**
* Token metadata input (name, symbol, description)
* Image upload and processing
* Social media links integration
* Initial buy amount configuration
* Automatic metadata upload to IPFS
* RugCheck verification submission
**`PumpfunBuySection`** & **`PumpfunSellSection`** - Trading interfaces
```typescript
import { PumpfunBuySection, PumpfunSellSection } from '@/modules/pump-fun';
function TradingInterface() {
const handleTradeComplete = (result) => {
console.log('Trade completed:', result);
};
return (
);
}
```
**Features:**
* Intelligent routing (Pump.fun → Raydium)
* Bonding curve visualization
* Portfolio integration
* Slippage configuration
* Real-time price updates
**`PumpSwapScreen`** - Complete AMM interface with tabs
```typescript
import { PumpSwapScreen } from '@/modules/pump-fun';
function AMMInterface() {
return (
);
}
```
**Features:**
* Multi-tab interface (Swap, Add/Remove Liquidity, Create Pool)
* Real-time quotes and pricing
* Liquidity position management
* Pool analytics and stats
* Transaction status tracking
Granular control with individual AMM components
```typescript
import {
SwapSection,
LiquidityAddSection,
PoolCreationSection
} from '@/modules/pump-fun/components/pump-swap';
function CustomAMMInterface() {
return (
);
}
```
## Core Hook: usePumpFun
The primary hook for Pump.fun interactions:
```typescript
import { usePumpFun } from '@/modules/pump-fun';
import { useWallet } from '@/modules/wallet-providers';
function PumpfunTradingComponent() {
const { wallet } = useWallet();
const {
launchToken,
buyToken,
sellToken,
submitTokenForVerification,
loading,
error
} = usePumpFun();
const handleLaunchToken = async (tokenData) => {
try {
const result = await launchToken({
name: tokenData.name,
symbol: tokenData.symbol,
description: tokenData.description,
image: tokenData.image,
socialLinks: tokenData.socialLinks,
initialBuy: tokenData.initialBuy
});
console.log('Token launched:', result);
// Automatically submit for verification
await submitTokenForVerification(result.mint);
} catch (error) {
console.error('Launch failed:', error);
}
};
const handleBuyToken = async (mint, amount) => {
try {
const result = await buyToken(mint, amount);
console.log('Purchase successful:', result);
} catch (error) {
console.error('Buy failed:', error);
}
};
return (
);
}
```
**Hook Functions:**
* `launchToken(params)` - Create and launch new token
* `buyToken(mint, amount)` - Purchase tokens
* `sellToken(mint, amount)` - Sell tokens
* `submitTokenForVerification(mint)` - Submit to RugCheck
## Services Overview
**`pumpfunService.ts`** - Direct Pump.fun platform integration
```typescript
import { pumpfunService } from '@/modules/pump-fun';
// Create and buy token in one transaction
const launchResult = await pumpfunService.createAndBuyTokenViaPumpfun({
name: 'My Meme Token',
symbol: 'MMT',
description: 'The best meme token ever!',
image: imageFile,
website: 'https://example.com',
twitter: '@mymemetoken',
telegram: 't.me/mymemetoken',
initialBuy: 0.1 // SOL amount
});
// Buy existing token (auto-detects Pump.fun vs Raydium)
const buyResult = await pumpfunService.buyTokenViaPumpfun(
tokenMint,
amountSol,
wallet,
onStatusUpdate
);
// Sell tokens
const sellResult = await pumpfunService.sellTokenViaPumpfun(
tokenMint,
tokenAmount,
wallet,
onStatusUpdate
);
```
**Key Features:**
* Metadata upload to IPFS via backend
* Intelligent routing between Pump.fun and Raydium
* Bonding curve interaction
* Commission handling
* Status update callbacks
**`pumpSwapService.ts`** - AMM operations via backend SDK wrapper
```typescript
import { pumpSwapService } from '@/modules/pump-fun';
// Create new liquidity pool
const pool = await pumpSwapService.createPool({
tokenA: 'So11111111111111111111111111111111111111112', // SOL
tokenB: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
initialLiquidityA: 1.0,
initialLiquidityB: 100.0,
feeBps: 30 // 0.3%
});
// Add liquidity to existing pool
const addResult = await pumpSwapService.addLiquidity({
poolAddress: poolAddress,
tokenAAmount: 0.5,
tokenBAmount: 50.0,
slippageBps: 100 // 1%
});
// Execute token swap
const swapResult = await pumpSwapService.swapTokens({
poolAddress: poolAddress,
inputToken: tokenA,
outputToken: tokenB,
amount: 1.0,
slippageBps: 50
});
// Get swap quote
const quote = await pumpSwapService.getSwapQuoteFromBase({
poolAddress: poolAddress,
baseAmount: 1.0
});
```
**Key Features:**
* Pool creation and management
* Liquidity provision and removal
* Token swapping with quotes
* Real-time pricing data
* Slippage protection
## Quick Start Examples
```typescript Complete Token Launch
import { usePumpFun } from '@/modules/pump-fun';
import { useWallet } from '@/modules/wallet-providers';
function MemeLaunchPlatform() {
const { wallet } = useWallet();
const { launchToken, submitTokenForVerification } = usePumpFun();
const [launching, setLaunching] = useState(false);
const handleLaunchMeme = async (formData) => {
if (!wallet) return;
setLaunching(true);
try {
// Launch the token
const result = await launchToken({
name: formData.name,
symbol: formData.symbol,
description: formData.description,
image: formData.image,
website: formData.website,
twitter: formData.twitter,
telegram: formData.telegram,
initialBuy: formData.initialBuy || 0.1
});
console.log('🚀 Token launched:', result);
// Submit for RugCheck verification
await submitTokenForVerification(result.mint);
Alert.alert(
'Success!',
`${formData.name} launched successfully!\nMint: ${result.mint}`
);
} catch (error) {
Alert.alert('Launch Failed', error.message);
} finally {
setLaunching(false);
}
};
return (
Launch Your Meme Token
{!wallet && (
)}
);
}
```
```typescript Trading Interface
import { PumpfunBuySection, PumpfunSellSection } from '@/modules/pump-fun';
function MemeTokenTrading() {
const [activeTab, setActiveTab] = useState('buy');
const [selectedToken, setSelectedToken] = useState(null);
const handleTradeSuccess = (result, type) => {
Alert.alert(
`${type} Successful!`,
`Transaction completed: ${result.signature}`
);
// Refresh portfolio or price data
if (type === 'Buy') {
refetchPortfolio();
}
};
return (
setActiveTab('buy')}
>
Buy setActiveTab('sell')}
>
Sell
{activeTab === 'buy' ? (
handleTradeSuccess(result, 'Buy')}
showBondingCurve={true}
/>
) : (
handleTradeSuccess(result, 'Sell')}
showPortfolio={true}
/>
)}
);
}
```
```typescript PumpSwap AMM Usage
import { PumpSwapScreen } from '@/modules/pump-fun';
import { useWallet } from '@/modules/wallet-providers';
function AMMPlatform() {
const { wallet } = useWallet();
const [pools, setPools] = useState([]);
useEffect(() => {
loadUserPools();
}, [wallet?.address]);
const loadUserPools = async () => {
if (!wallet) return;
try {
// Load user's liquidity positions
const userPools = await pumpSwapService.getUserLiquidityPositions(
wallet.address
);
setPools(userPools);
} catch (error) {
console.error('Failed to load pools:', error);
}
};
const handleSwapComplete = (result) => {
console.log('Swap completed:', result);
loadUserPools(); // Refresh positions
};
const handleLiquidityAdded = (result) => {
console.log('Liquidity added:', result);
loadUserPools(); // Refresh positions
};
const handlePoolCreated = (result) => {
console.log('Pool created:', result);
loadUserPools(); // Refresh positions
};
return (
PumpSwap AMM
{pools.length > 0 && (
Your Liquidity Positions
{pools.map((pool, index) => (
))}
)}
);
}
```
## Advanced Features
### Intelligent Token Routing
The module automatically detects whether tokens are on Pump.fun bonding curves or have migrated to Raydium:
```typescript
function useIntelligentTrading() {
const { buyToken } = usePumpFun();
const smartBuy = async (tokenMint, amount) => {
try {
// Service automatically checks:
// 1. Is token still on Pump.fun bonding curve?
// 2. Has it migrated to Raydium?
// 3. Routes to appropriate platform
const result = await buyToken(tokenMint, amount);
console.log(`Purchased via ${result.platform}:`, result);
return result;
} catch (error) {
console.error('Smart buy failed:', error);
throw error;
}
};
return { smartBuy };
}
```
### Bonding Curve Visualization
```typescript
function BondingCurveChart({ tokenMint }) {
const [curveData, setCurveData] = useState(null);
useEffect(() => {
loadBondingCurveData();
}, [tokenMint]);
const loadBondingCurveData = async () => {
try {
const data = await pumpfunService.getBondingCurveData(tokenMint);
setCurveData(data);
} catch (error) {
console.error('Failed to load bonding curve:', error);
}
};
return (
Bonding Curve Progress
{curveData && (
{(curveData.progress * 100).toFixed(1)}% to Raydium migration
Current Price: {curveData.currentPrice} SOL
)}
);
}
```
### Social Integration & Verification
```typescript
function useSocialTokenLaunch() {
const { launchToken, submitTokenForVerification } = usePumpFun();
const { createPost } = useThread();
const launchAndAnnounce = async (tokenData) => {
try {
// Launch the token
const result = await launchToken(tokenData);
// Submit for verification
await submitTokenForVerification(result.mint);
// Create social post
await createPost({
content: `🚀 Just launched ${tokenData.name} ($${tokenData.symbol})!\n\n${tokenData.description}`,
type: 'token_launch',
attachments: [
{
type: 'token',
mint: result.mint,
name: tokenData.name,
symbol: tokenData.symbol,
image: tokenData.image
}
]
});
return result;
} catch (error) {
console.error('Launch and announce failed:', error);
throw error;
}
};
return { launchAndAnnounce };
}
```
## Utility Functions
**`pumpfunUtils.ts`** - Pump.fun specific helpers
```typescript
import {
checkIfTokenIsOnRaydium,
buildPumpFunBuyTransaction,
getSwapQuote
} from '@/modules/pump-fun/utils';
// Check if token has migrated to Raydium
const isOnRaydium = await checkIfTokenIsOnRaydium(tokenMint);
// Build Pump.fun transaction
const transaction = await buildPumpFunBuyTransaction({
mint: tokenMint,
amount: amountSol,
slippage: 0.5
});
// Get swap quote
const quote = await getSwapQuote(inputToken, outputToken, amount);
```
**`pumpSwapUtils.ts`** - AMM calculations and formatting
```typescript
import {
calculateSlippage,
formatTokenAmount,
calculateFees
} from '@/modules/pump-fun/utils';
// Calculate slippage impact
const slippageImpact = calculateSlippage(inputAmount, outputAmount, marketPrice);
// Format token amounts for display
const formatted = formatTokenAmount(amount, decimals);
// Calculate pool fees
const fees = calculateFees(amount, feeBps);
```
**`anchorMobilePatch.ts`** - React Native wallet compatibility
```typescript
import { MobileWallet } from '@/modules/pump-fun/utils';
// Use instead of NodeWallet for React Native compatibility
const mobileWallet = new MobileWallet(wallet);
```
## Integration with Other Modules
Transaction signing and wallet management for token operations
Real-time token prices and portfolio tracking
Social sharing of token launches and trading activity
Token-gated NFT access and community rewards
### Combined Workflow Example
```typescript
import { useWallet } from '@/modules/wallet-providers';
import { useFetchTokens } from '@/modules/data-module';
import { useThread } from '@/core/thread';
import { usePumpFun } from '@/modules/pump-fun';
function IntegratedMemeplatform() {
const { wallet } = useWallet();
const { refetch: refetchTokens } = useFetchTokens(wallet?.address);
const { createPost } = useThread();
const { launchToken, submitTokenForVerification } = usePumpFun();
const handleMemeLaunch = async (tokenData) => {
try {
// Launch token
const result = await launchToken(tokenData);
// Refresh user's portfolio
await refetchTokens();
// Submit for verification
await submitTokenForVerification(result.mint);
// Create announcement post
await createPost({
content: `🚀 Just launched my meme token ${tokenData.name}! Who's ready to pump it? 📈`,
type: 'token_launch',
sections: [
{
type: 'trade',
data: {
tokenAddress: result.mint,
action: 'buy',
platform: 'pump.fun'
}
}
]
});
return result;
} catch (error) {
console.error('Integrated launch failed:', error);
throw error;
}
};
return ;
}
```
## Error Handling & Troubleshooting
**Backend Connection Failures**
* Verify `SERVER_URL` is correctly configured
* Ensure backend service is running
* Check network connectivity
**Transaction Failures**
* Insufficient SOL for transaction fees
* Slippage tolerance too low
* Network congestion
* Wallet connection issues
**Token Launch Issues**
* Image upload failures
* Metadata formatting errors
* Invalid social media links
* Commission wallet configuration
**AMM Operation Failures**
* Pool doesn't exist
* Insufficient liquidity
* Price impact too high
* Invalid token addresses
```typescript
function RobustPumpfunOperations() {
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 3;
const safeOperation = async (operation, params) => {
try {
return await operation(params);
} catch (error) {
console.error('Operation failed:', error);
if (retryCount < maxRetries && error.message.includes('network')) {
setRetryCount(prev => prev + 1);
await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
return safeOperation(operation, params);
}
throw error;
}
};
return { safeOperation };
}
```
## Performance Considerations
**Backend Optimization**: Use backend services for heavy SDK operations to improve mobile app performance and reduce bundle size.
**Rate Limits**: Be mindful of API rate limits when making frequent price updates or metadata requests.
## API Reference
For detailed API documentation, see:
* [Pump.fun Components Reference](/docs/references/modules/pump-fun/components)
* [Services Reference](/docs/references/modules/pump-fun/services)
* [Hooks Reference](/docs/references/modules/pump-fun/hooks)
* [Types Reference](/docs/references/modules/pump-fun/types)
***
The Pump.fun module provides everything needed to build a complete meme token ecosystem, from viral token launches to sophisticated AMM trading, all with built-in social features and community verification.
# Raydium Module
Source: https://docs.solanaappkit.com/docs/modules/raydium
Professional token launching and swapping with Raydium's advanced Launchpad and AMM platform
The Raydium module provides comprehensive integration with Raydium's platform, featuring professional token launching through their Launchpad and sophisticated swapping capabilities via their AMM infrastructure.
## Core Functionalities
Simplified token launch with pre-configured settings for quick deployment with industry standards
Advanced token configuration with custom bonding curves, vesting schedules, and pool parameters
Execute efficient token swaps via Raydium's advanced AMM with optimal price discovery
Automated migration from bonding curves to AMM or CPMM pools with configurable parameters
## Installation & Setup
Ensure your backend server is running for Raydium SDK operations:
```bash
SERVER_URL=http://localhost:8080/api
```
Configure Raydium-specific settings in `.env.local`:
```bash
SERVER_URL=your_backend_server_url
HELIUS_STAKED_URL=your_rpc_endpoint
CLUSTER=mainnet-beta
```
Import the components and services you need:
```typescript
import {
LaunchlabsScreen,
LaunchlabsLaunchSection,
AdvancedOptionsSection,
raydiumService
} from '@/modules/raydium';
```
**Backend Dependency**: This module requires a backend service that implements Raydium SDK operations for token creation and swapping.
## Module Architecture
```
src/modules/raydium/
├── components/ # UI components for token launching
├── screens/ # Complete screen implementations
├── services/ # Raydium API integration
├── utils/ # Advanced configuration utilities
└── index.ts # Public API exports
```
## Core Components
**`LaunchlabsScreen`** - Complete token launching interface
```typescript
import { LaunchlabsScreen } from '@/modules/raydium';
function TokenLaunchPlatform() {
const handleTokenLaunched = (result) => {
console.log('Token launched:', result);
// Handle success (navigation, notifications, etc.)
};
return (
);
}
```
**Features:**
* Two-step launch process (basic info → advanced config)
* Mode selection (JustSendIt vs LaunchLab)
* Real-time validation and preview
* Integrated metadata upload
**`LaunchlabsLaunchSection`** - Token information input interface
```typescript
import { LaunchlabsLaunchSection } from '@/modules/raydium';
function TokenInfoStep() {
const handleInfoComplete = (tokenData) => {
console.log('Token info completed:', tokenData);
// Move to next step
};
return (
);
}
```
**Features:**
* Token metadata input (name, symbol, description)
* Image upload with preview
* Social media links configuration
* Launch mode selection
* Form validation and error handling
**`AdvancedOptionsSection`** - Comprehensive launch configuration
```typescript
import { AdvancedOptionsSection } from '@/modules/raydium';
function AdvancedConfigStep({ tokenData }) {
const handleConfigComplete = (config) => {
console.log('Advanced config completed:', config);
// Execute token launch
};
return (
);
}
```
**Features:**
* Quote token selection (SOL, USDC, etc.)
* Supply and pricing configuration
* Bonding curve percentage (51%-80%)
* Vesting schedules (0%-30%)
* Pool migration settings (AMM vs CPMM)
* Fee sharing configuration
* Real-time bonding curve visualization
## Launch Modes
**Quick Launch** - Pre-configured for immediate deployment
```typescript
const justSendItConfig = {
mode: 'JustSendIt',
supply: 1000000000, // 1B tokens
ammThreshold: 85, // 85 SOL
bondingCurvePercentage: 51, // 51% on bonding curve
vestingPercentage: 0, // No vesting
quoteToken: 'SOL',
poolType: 'AMM',
slippage: 0.5
};
const result = await raydiumService.createAndLaunchToken({
...tokenData,
config: justSendItConfig
});
```
**Standard Configuration:**
* 1 Billion token supply
* 85 SOL AMM threshold
* 51% on bonding curve
* No vesting period
* SOL as quote token
* AMM pool migration
**Advanced Configuration** - Full customization control
```typescript
const launchLabConfig = {
mode: 'LaunchLab',
quoteToken: 'USDC',
supply: 500000000,
solToBeRaised: 100,
bondingCurvePercentage: 65,
vestingPercentage: 20,
vestingSchedule: {
duration: 12,
cliff: 3,
timeUnit: 'months'
},
poolType: 'CPMM',
feeSharing: true,
slippage: 1.0,
enableInitialBuy: true,
initialBuyAmount: 5
};
const result = await raydiumService.createAndLaunchToken({
...tokenData,
config: launchLabConfig
});
```
**Customizable Options:**
* Quote token selection
* Custom token supply
* SOL fundraising target
* Bonding curve percentage (51%-80%)
* Vesting percentage (0%-30%)
* Flexible vesting schedules
* Pool migration type selection
* Fee sharing for CPMM pools
* Initial buy configuration
## Raydium Services
The `raydiumService.ts` provides comprehensive Raydium platform integration:
```typescript
import { raydiumService } from '@/modules/raydium';
// Upload token metadata to IPFS
const metadataUri = await raydiumService.uploadTokenMetadata({
name: 'My Token',
symbol: 'MTK',
description: 'A professional token built on Raydium',
image: imageFile,
website: 'https://mytoken.com',
twitter: '@mytoken',
telegram: 't.me/mytoken'
});
// Launch token with full configuration
const launchResult = await raydiumService.createAndLaunchToken({
// Basic token data
name: 'My Token',
symbol: 'MTK',
description: 'A professional token built on Raydium',
image: imageFile,
metadataUri: metadataUri,
// Advanced configuration
config: {
mode: 'LaunchLab',
quoteToken: 'SOL',
supply: 1000000000,
solToBeRaised: 200,
bondingCurvePercentage: 70,
vestingPercentage: 15,
vestingSchedule: {
duration: 6,
cliff: 1,
timeUnit: 'months'
},
poolType: 'CPMM',
feeSharing: true,
slippage: 0.5,
enableInitialBuy: true,
initialBuyAmount: 10
}
});
```
**Available Functions:**
* `uploadTokenMetadata()` - Upload metadata to IPFS
* `createAndLaunchToken()` - Complete token launch process
* Status callbacks for real-time updates
* Error handling and validation
```typescript
// Execute token swap via Raydium
const swapResult = await raydiumService.executeSwap({
inputToken: 'So11111111111111111111111111111111111111112', // SOL
outputToken: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
amount: 1.0,
slippage: 0.5,
userPublicKey: wallet.publicKey
});
console.log('Swap completed:', swapResult);
```
**Swap Features:**
* Optimal routing through Raydium pools
* Slippage protection
* Real-time quotes
* Transaction status tracking
## Quick Start Examples
```typescript Simple Token Launch (JustSendIt)
import { LaunchlabsScreen } from '@/modules/raydium';
import { useWallet } from '@/modules/wallet-providers';
function QuickTokenLaunch() {
const { wallet } = useWallet();
const [launching, setLaunching] = useState(false);
const handleQuickLaunch = async (tokenData) => {
if (!wallet) return;
setLaunching(true);
try {
// Use JustSendIt mode for quick launch
const result = await raydiumService.createAndLaunchToken({
...tokenData,
config: {
mode: 'JustSendIt',
enableInitialBuy: true,
initialBuyAmount: 1 // 1 SOL initial buy
}
});
Alert.alert(
'Token Launched!',
`${tokenData.name} successfully launched on Raydium!\nMint: ${result.mint}`
);
} catch (error) {
Alert.alert('Launch Failed', error.message);
} finally {
setLaunching(false);
}
};
return (
Quick Token Launch
Launch with industry-standard settings
);
}
```
```typescript Advanced Token Launch (LaunchLab)
import {
LaunchlabsLaunchSection,
AdvancedOptionsSection
} from '@/modules/raydium';
function AdvancedTokenLaunch() {
const [step, setStep] = useState(1);
const [tokenData, setTokenData] = useState(null);
const [config, setConfig] = useState(null);
const handleBasicInfoComplete = (data) => {
setTokenData(data);
setStep(2);
};
const handleAdvancedConfigComplete = async (advancedConfig) => {
setConfig(advancedConfig);
try {
const result = await raydiumService.createAndLaunchToken({
...tokenData,
config: advancedConfig
});
console.log('Advanced token launched:', result);
Alert.alert(
'Professional Launch Complete!',
`${tokenData.name} launched with custom configuration`
);
} catch (error) {
Alert.alert('Launch Failed', error.message);
}
};
return (
{step === 1 ? (
{
if (mode === 'JustSendIt') {
// Handle quick launch
}
}}
/>
) : (
setStep(1)}
/>
)}
);
}
```
```typescript Token Swapping
import { raydiumService } from '@/modules/raydium';
import { useWallet } from '@/modules/wallet-providers';
function RaydiumSwapInterface() {
const { wallet } = useWallet();
const [inputToken, setInputToken] = useState('SOL');
const [outputToken, setOutputToken] = useState('USDC');
const [amount, setAmount] = useState('');
const [quote, setQuote] = useState(null);
const [swapping, setSwapping] = useState(false);
useEffect(() => {
if (amount && parseFloat(amount) > 0) {
fetchQuote();
}
}, [inputToken, outputToken, amount]);
const fetchQuote = async () => {
try {
// This would typically involve calling a quote endpoint
const quoteData = await getSwapQuote(inputToken, outputToken, amount);
setQuote(quoteData);
} catch (error) {
console.error('Quote failed:', error);
}
};
const handleSwap = async () => {
if (!wallet || !quote) return;
setSwapping(true);
try {
const result = await raydiumService.executeSwap({
inputToken: inputToken,
outputToken: outputToken,
amount: parseFloat(amount),
slippage: 0.5,
userPublicKey: wallet.publicKey
});
Alert.alert(
'Swap Successful!',
`Swapped ${amount} ${inputToken} for ${result.outputAmount} ${outputToken}`
);
} catch (error) {
Alert.alert('Swap Failed', error.message);
} finally {
setSwapping(false);
}
};
return (
Raydium Swap
{quote && (
You'll receive: ~{quote.outputAmount} {outputToken}Rate: 1 {inputToken} = {quote.rate} {outputToken}Price Impact: {quote.priceImpact}%
)}
);
}
```
## Advanced Configuration Utilities
The `AdvancedOptionsSectionUtils.tsx` provides comprehensive utilities for token launch configuration:
```typescript
import {
validateBondingCurvePercentage,
validateVestingPercentage,
validateSolRaised,
calculatePoolMigrationPercentage
} from '@/modules/raydium/utils';
// Validate bonding curve percentage (51%-80%)
const isValidBondingCurve = validateBondingCurvePercentage(65);
// Validate vesting percentage (0%-30%)
const isValidVesting = validateVestingPercentage(20);
// Validate SOL to be raised
const isValidSolRaised = validateSolRaised(100);
// Calculate pool migration percentage
const poolMigration = calculatePoolMigrationPercentage(65, 20);
// Returns: 15% (100% - 65% bonding - 20% vesting)
```
```typescript
import {
calculateGraphData,
convertVestingPeriodToSeconds,
formatNumber,
parseNumericString
} from '@/modules/raydium/utils';
// Generate bonding curve graph data
const graphData = calculateGraphData({
supply: 1000000000,
solRaised: 100,
bondingCurvePercentage: 65
});
// Convert vesting period to seconds
const vestingSeconds = convertVestingPeriodToSeconds(6, 'months');
// Format numbers for display
const formatted = formatNumber(1000000); // Returns: "1,000,000"
// Parse numeric strings
const parsed = parseNumericString('1,000.50'); // Returns: 1000.5
```
```typescript
import {
TOKEN_SUPPLY_OPTIONS,
TIME_UNIT_OPTIONS,
SAMPLE_TOKENS
} from '@/modules/raydium/utils';
// Predefined supply options
console.log(TOKEN_SUPPLY_OPTIONS);
// [100000000, 500000000, 1000000000, 5000000000, 10000000000]
// Time unit options for vesting
console.log(TIME_UNIT_OPTIONS);
// ['days', 'weeks', 'months', 'years']
// Sample tokens for testing/demo
console.log(SAMPLE_TOKENS);
// Array of sample token configurations
```
## Bonding Curve Visualization
The module includes real-time bonding curve visualization:
```typescript
function BondingCurvePreview({ config }) {
const [graphData, setGraphData] = useState([]);
useEffect(() => {
const data = calculateGraphData({
supply: config.supply,
solRaised: config.solRaised,
bondingCurvePercentage: config.bondingCurvePercentage
});
setGraphData(data);
}, [config]);
return (
Bonding Curve Preview `rgba(25, 255, 146, ${opacity})`,
}}
/>
Starting Price: {graphData[0]?.price || 0} SOLMigration Price: {graphData[graphData.length - 1]?.price || 0} SOLTokens on Curve: {config.bondingCurvePercentage}%
);
}
```
## Integration with Other Modules
Transaction signing and wallet management for token operations
Real-time token data and portfolio tracking integration
Social sharing of professional token launches
Cross-DEX arbitrage and trading opportunities
### Professional Launch Workflow
```typescript
import { useWallet } from '@/modules/wallet-providers';
import { useFetchTokens } from '@/modules/data-module';
import { useThread } from '@/core/thread';
import { raydiumService } from '@/modules/raydium';
function ProfessionalTokenPlatform() {
const { wallet } = useWallet();
const { refetch: refetchTokens } = useFetchTokens(wallet?.address);
const { createPost } = useThread();
const handleProfessionalLaunch = async (tokenData, config) => {
try {
// Launch token with advanced configuration
const result = await raydiumService.createAndLaunchToken({
...tokenData,
config
});
// Refresh user's portfolio
await refetchTokens();
// Create professional announcement
await createPost({
content: `🏗️ Just launched ${tokenData.name} on @RaydiumProtocol with professional-grade tokenomics!\n\n📊 Bonding Curve: ${config.bondingCurvePercentage}%\n⏰ Vesting: ${config.vestingPercentage}% over ${config.vestingSchedule.duration} ${config.vestingSchedule.timeUnit}\n💰 Target: ${config.solRaised} SOL`,
type: 'professional_launch',
sections: [
{
type: 'trade',
data: {
tokenAddress: result.mint,
action: 'buy',
platform: 'raydium',
launchType: 'professional'
}
}
]
});
return result;
} catch (error) {
console.error('Professional launch failed:', error);
throw error;
}
};
return ;
}
```
## Error Handling & Troubleshooting
**Backend Connection Issues**
* Verify `SERVER_URL` is correctly configured
* Ensure Raydium backend service is running
* Check network connectivity and firewall settings
**Token Launch Failures**
* Invalid bonding curve parameters (must be 51%-80%)
* Vesting percentage too high (max 30%)
* Insufficient SOL for transaction fees
* Metadata upload failures
**Configuration Errors**
* Pool migration percentage calculation errors
* Invalid vesting schedule parameters
* Quote token not supported
* AMM vs CPMM pool type mismatch
**Swap Failures**
* Insufficient liquidity for large swaps
* Slippage tolerance too low
* Token not available on Raydium
* Network congestion issues
```typescript
function RobustRaydiumOperations() {
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 3;
const safeRaydiumOperation = async (operation, params) => {
try {
return await operation(params);
} catch (error) {
console.error('Raydium operation failed:', error);
if (retryCount < maxRetries && error.message.includes('network')) {
setRetryCount(prev => prev + 1);
const delay = 1000 * Math.pow(2, retryCount); // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay));
return safeRaydiumOperation(operation, params);
}
// Handle specific Raydium errors
if (error.message.includes('bonding curve')) {
throw new Error('Invalid bonding curve configuration. Please adjust parameters.');
}
if (error.message.includes('vesting')) {
throw new Error('Vesting percentage must be between 0% and 30%.');
}
throw error;
}
};
return { safeRaydiumOperation };
}
```
## Performance Considerations
**Configuration Validation**: Use the provided validation functions to ensure parameters are valid before launching to avoid transaction failures.
**Backend Optimization**: Complex token launches involve multiple transactions. Ensure your backend can handle the load and has proper error recovery.
## API Reference
For detailed API documentation, see:
* [Raydium Components Reference](/docs/references/modules/raydium/components)
* [Services Reference](/docs/references/modules/raydium/services)
* [Utils Reference](/docs/references/modules/raydium/utils)
***
The Raydium module provides professional-grade token launching capabilities with sophisticated configuration options, making it ideal for serious projects requiring advanced tokenomics and institutional-quality infrastructure.
# SendAI Module
Source: https://docs.solanaappkit.com/docs/modules/solana-agent-kit
AI-powered Solana interactions with intelligent chat interfaces and automated blockchain operations
The Solana Agent Kit module provides a comprehensive AI-powered toolkit that enables natural language interactions with the Solana blockchain. Users can chat with an AI agent that understands Solana operations and can execute transactions, check balances, and perform complex DeFi operations through conversational interfaces.
## Core Functionalities
Advanced chat system with streaming responses, message persistence, and context management
Direct blockchain interactions through AI commands including transactions, transfers, and DeFi operations
Extensible plugin system for adding custom Solana functionality and third-party integrations
Intelligent automation of complex multi-step Solana operations through natural language commands
## Installation & Setup
Configure your OpenAI API key for AI model access:
```bash
OPENAI_API_KEY=your_openai_api_key_here
```
Set up Solana RPC and backend endpoints:
```bash
HELIUS_STAKED_URL=your_solana_rpc_endpoint
SERVER_URL=your_backend_server_url
```
Import the chat hook and utilities:
```typescript
import {
useChat,
myProvider,
generateUUID
} from '@/modules/solana-agent-kit';
```
Ensure wallet providers are configured:
```typescript
import { useWallet } from '@/modules/wallet-providers';
```
**AI Model Access**: This module requires an OpenAI API key for full functionality. The system gracefully handles missing keys but AI features will be disabled.
## Module Architecture
```
src/modules/solana-agent-kit/
├── hooks/ # React hooks for chat management
│ └── useChat.ts # Core chat functionality
├── lib/ # AI and utility libraries
│ ├── ai/
│ │ └── providers.ts # AI model configuration
│ └── utils.ts # Persistence and utility functions
└── index.ts # Public API exports
```
## Core Hook: useChat
The primary interface for AI-powered Solana interactions:
```typescript
import { useChat } from '@/modules/solana-agent-kit';
import { useWallet } from '@/modules/wallet-providers';
function AIAssistantChat() {
const { connected } = useWallet();
const {
messages,
input,
handleInputChange,
handleSubmit,
isLoading,
error,
currentOperation,
append,
reload,
stop
} = useChat({
id: 'unique-chat-id',
initialMessages: [],
onFinish: (message) => {
console.log('AI response completed:', message);
},
onError: (error) => {
console.error('Chat error:', error);
}
});
if (!connected) {
return (
Please connect your wallet to use the AI Agent
);
}
return (
);
}
```
**Hook Parameters:**
* `id` - Unique chat session identifier
* `initialMessages` - Pre-existing message history
* `onFinish` - Callback when AI completes response
* `onError` - Error handling callback
**Hook Returns:**
* `messages` - Array of chat messages
* `input` - Current input text
* `handleInputChange` - Input change handler
* `handleSubmit` - Message submission function
* `isLoading` - Loading state
* `error` - Error message if any
* `currentOperation` - Current AI operation status
* `append` - Add message programmatically
* `reload` - Regenerate last AI response
* `stop` - Stop current AI generation
## AI Model Configuration
The module uses advanced AI models through custom providers:
**Chat and Reasoning Models**
```typescript
import { myProvider } from '@/modules/solana-agent-kit';
// Available language models
const models = {
chat: 'gpt-4o', // Main chat model
title: 'gpt-3.5-turbo', // Title generation
reasoning: 'gpt-4o', // Complex reasoning
fallback: 'gpt-3.5-turbo' // Backup model
};
// Custom provider configuration
const provider = myProvider({
apiKey: process.env.OPENAI_API_KEY,
models: models
});
```
**Advanced AI Capabilities**
* **Streaming Responses**: Real-time message generation
* **Context Awareness**: Maintains conversation history
* **Reasoning Middleware**: Enhanced decision-making
* **Function Calling**: Direct integration with Solana tools
* **Error Recovery**: Automatic retry and fallback mechanisms
* **Multi-model Support**: Different models for different tasks
## Solana Agent Capabilities
The AI agent can perform various Solana operations through natural language:
```typescript
// Example user queries the AI can handle:
"Send 0.5 SOL to 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"
"Check my SOL balance"
"What tokens do I own?"
"Swap 1 SOL for USDC"
"Show me my transaction history"
// The AI automatically:
// 1. Parses the user intent
// 2. Constructs appropriate transactions
// 3. Requests user approval
// 4. Executes the operation
// 5. Provides confirmation and details
```
**Available Operations:**
* Send SOL and SPL tokens
* Check balances and portfolios
* View transaction history
* Sign messages and transactions
* Multi-transaction operations
```typescript
// Advanced DeFi queries:
"Create a new token with 1M supply"
"Add liquidity to SOL/USDC pool"
"Stake my SOL for rewards"
"Check my DeFi positions"
"Find the best swap rate for 100 USDC to SOL"
// Integration with other modules:
// - Token creation via Pump.fun or Raydium
// - Liquidity operations via Meteora
// - NFT operations via Tensor
// - Cross-DEX arbitrage opportunities
```
**DeFi Capabilities:**
* Token creation and management
* Liquidity provision and farming
* Staking and delegation
* Cross-protocol interactions
* Yield optimization suggestions
```typescript
// Portfolio analysis queries:
"Analyze my portfolio performance"
"What's my total portfolio value?"
"Show me my biggest gains and losses"
"Suggest portfolio rebalancing"
"Track my token allocations"
// AI provides:
// - Real-time portfolio valuation
// - Performance analytics
// - Risk assessment
// - Rebalancing suggestions
// - Tax optimization tips
```
**Portfolio Features:**
* Real-time valuation tracking
* Performance analytics
* Risk assessment and management
* Automated rebalancing suggestions
* Tax optimization strategies
## Quick Start Examples
```typescript Basic AI Chat Interface
import { useChat } from '@/modules/solana-agent-kit';
import { useWallet } from '@/modules/wallet-providers';
function SolanaAIAssistant() {
const { connected } = useWallet();
const {
messages,
input,
handleInputChange,
handleSubmit,
isLoading,
currentOperation
} = useChat({
id: 'main-chat',
onFinish: (message) => {
// Handle completion
console.log('AI completed:', message.content);
}
});
return (
Solana AI Assistant
{!connected && (
Connect your wallet to start chatting with the AI
)}
item.id}
renderItem={({ item }) => (
)}
style={styles.messagesList}
/>
{currentOperation && (
{currentOperation}
)}
{isLoading ? "..." : "Send"}
);
}
```
```typescript Advanced Chat with Persistence
import { useChat, generateUUID, saveChat } from '@/modules/solana-agent-kit';
function PersistentChatInterface() {
const [chatId] = useState(() => generateUUID());
const {
messages,
input,
handleInputChange,
handleSubmit,
isLoading
} = useChat({
id: chatId,
onFinish: async (message) => {
// Auto-save important conversations
if (messages.length > 10) {
await saveChat({
id: chatId,
title: generateChatTitle(messages),
messages: messages,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
});
}
}
});
const generateChatTitle = (messages) => {
const firstUserMessage = messages.find(m => m.role === 'user');
return firstUserMessage?.content.slice(0, 50) + '...' || 'New Chat';
};
const handleSaveChat = async () => {
try {
const title = await generateTitleFromUserMessage(messages[0]?.content || 'Saved Chat');
await saveChat({
id: chatId,
title,
messages,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
});
Alert.alert('Success', 'Chat saved successfully!');
} catch (error) {
Alert.alert('Error', 'Failed to save chat');
}
};
return (
AI AssistantSave Chat
);
}
```
```typescript Custom AI Operations
import { useChat } from '@/modules/solana-agent-kit';
import { useWallet } from '@/modules/wallet-providers';
function CustomSolanaOperations() {
const { wallet, signTransaction, sendTransaction } = useWallet();
const { append, messages } = useChat({
id: 'custom-operations',
onToolCall: async (toolCall) => {
// Custom handling for specific AI tool calls
console.log('AI wants to use tool:', toolCall.toolName);
if (toolCall.toolName === 'signTransaction') {
// Custom transaction confirmation UI
const confirmed = await showTransactionConfirmation(toolCall.args);
if (!confirmed) {
throw new Error('User cancelled transaction');
}
}
}
});
const handlePresetOperation = async (operation) => {
const presetQueries = {
portfolio: "Show me my complete portfolio with current values",
balance: "What's my SOL balance?",
history: "Show my recent transaction history",
defi: "What DeFi positions do I have?",
optimize: "Suggest ways to optimize my portfolio"
};
await append({
role: 'user',
content: presetQueries[operation]
});
};
return (
);
}
```
## Chat Persistence & Management
The module provides comprehensive chat management capabilities:
```typescript
import {
saveChat,
fetchChat,
fetchChats,
deleteChat
} from '@/modules/solana-agent-kit';
// Save chat to backend
const chatData = {
id: generateUUID(),
title: 'Portfolio Analysis Session',
messages: messages,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
await saveChat(chatData);
// Fetch specific chat
const chat = await fetchChat(chatId);
// Fetch all user chats
const userChats = await fetchChats();
// Delete chat
await deleteChat(chatId);
```
```typescript
import {
saveMessages,
fetchMessages,
standardizeMessageFormat
} from '@/modules/solana-agent-kit';
// Save messages with standardized format
const formattedMessages = messages.map(standardizeMessageFormat);
await saveMessages(chatId, formattedMessages);
// Fetch messages for a chat
const chatMessages = await fetchMessages(chatId);
// Convert for UI display
const uiMessages = convertToUIMessages(chatMessages);
```
```typescript
import { createOrUpdateUser } from '@/modules/solana-agent-kit';
// Create or update user profile
await createOrUpdateUser({
walletAddress: wallet.address,
preferences: {
aiModel: 'gpt-4o',
language: 'en',
notifications: true
},
lastActive: new Date().toISOString()
});
```
## Advanced AI Features
### Custom Tool Integration
```typescript
function useCustomSolanaTools() {
const { wallet } = useWallet();
const customTools = useMemo(() => {
if (!wallet) return [];
return createVercelAITools({
// Custom portfolio analysis tool
analyzePortfolio: {
description: 'Analyze user portfolio performance and provide insights',
parameters: z.object({
timeframe: z.enum(['1d', '7d', '30d', '90d', '1y']),
includeNFTs: z.boolean().default(false)
}),
execute: async ({ timeframe, includeNFTs }) => {
const analysis = await performPortfolioAnalysis(wallet.address, timeframe, includeNFTs);
return {
totalValue: analysis.totalValue,
gainLoss: analysis.gainLoss,
topPerformers: analysis.topPerformers,
recommendations: analysis.recommendations
};
}
},
// Custom yield farming finder
findYieldOpportunities: {
description: 'Find the best yield farming opportunities for user tokens',
parameters: z.object({
minAPY: z.number().default(5),
riskLevel: z.enum(['low', 'medium', 'high']).default('medium')
}),
execute: async ({ minAPY, riskLevel }) => {
const opportunities = await findYieldFarmingOpps(wallet.address, minAPY, riskLevel);
return opportunities;
}
}
});
}, [wallet]);
return customTools;
}
```
### Intelligent Transaction Batching
```typescript
function useIntelligentBatching() {
const { wallet, sendTransaction } = useWallet();
const batchTransactions = async (operations) => {
try {
// AI analyzes operations and optimizes batching
const optimizedBatches = await optimizeTransactionBatching(operations);
const results = [];
for (const batch of optimizedBatches) {
const batchResult = await executeTransactionBatch(batch);
results.push(batchResult);
}
return {
success: true,
results,
totalGasSaved: calculateGasSavings(operations, optimizedBatches)
};
} catch (error) {
console.error('Batch execution failed:', error);
throw error;
}
};
return { batchTransactions };
}
```
### Smart Risk Assessment
```typescript
function useRiskAssessment() {
const assessTransactionRisk = async (transaction) => {
try {
const analysis = await analyzeTransactionRisk(transaction);
return {
riskLevel: analysis.riskLevel, // 'low', 'medium', 'high'
factors: analysis.riskFactors,
recommendations: analysis.recommendations,
shouldProceed: analysis.riskLevel !== 'high'
};
} catch (error) {
console.error('Risk assessment failed:', error);
return { riskLevel: 'unknown', shouldProceed: false };
}
};
return { assessTransactionRisk };
}
```
## Integration with Other Modules
Essential for transaction signing and wallet state management
Real-time portfolio data and market information for AI analysis
AI can execute operations across Pump.fun, Raydium, Meteora, and more
AI can create posts about transactions and share insights
### Unified AI Trading Assistant
```typescript
import { useWallet } from '@/modules/wallet-providers';
import { useFetchTokens } from '@/modules/data-module';
import { useSwap } from '@/modules/swap';
import { usePumpFun } from '@/modules/pump-fun';
import { useChat } from '@/modules/solana-agent-kit';
function UnifiedTradingAssistant() {
const { wallet } = useWallet();
const { tokens, refetch } = useFetchTokens(wallet?.address);
const { executeSwap } = useSwap();
const { launchToken } = usePumpFun();
const { messages, handleSubmit, input, handleInputChange } = useChat({
id: 'trading-assistant',
onToolCall: async (toolCall) => {
switch (toolCall.toolName) {
case 'executeSwap':
const swapResult = await executeSwap(toolCall.args);
await refetch(); // Refresh portfolio
return swapResult;
case 'launchToken':
const launchResult = await launchToken(toolCall.args);
await refetch(); // Refresh portfolio
return launchResult;
case 'getPortfolio':
return tokens;
default:
throw new Error(`Unknown tool: ${toolCall.toolName}`);
}
}
});
return (
AI Trading Assistant
Ask me to analyze your portfolio, execute trades, or launch tokens
);
}
```
## Security & Best Practices
**Transaction Approval**: Always implement clear user confirmation for AI-initiated transactions. Never auto-execute without explicit user consent.
**Context Management**: The AI maintains conversation context, but be mindful of sensitive information in chat history.
```typescript
function SecureAITransactions() {
const { wallet } = useWallet();
const confirmTransaction = async (transaction) => {
return new Promise((resolve) => {
Alert.alert(
'Confirm Transaction',
`The AI wants to execute a transaction:\n\n${formatTransactionDetails(transaction)}\n\nDo you approve?`,
[
{ text: 'Cancel', onPress: () => resolve(false), style: 'cancel' },
{ text: 'Approve', onPress: () => resolve(true) }
]
);
});
};
const secureExecute = async (operation) => {
try {
// Risk assessment
const riskAssessment = await assessOperationRisk(operation);
if (riskAssessment.riskLevel === 'high') {
Alert.alert('High Risk Operation', riskAssessment.warning);
return;
}
// User confirmation
const confirmed = await confirmTransaction(operation.transaction);
if (!confirmed) {
throw new Error('User cancelled operation');
}
// Execute with monitoring
return await executeWithMonitoring(operation);
} catch (error) {
console.error('Secure execution failed:', error);
throw error;
}
};
return { secureExecute };
}
```
## Error Handling & Troubleshooting
**OpenAI API Issues**
* Invalid or missing API key
* Rate limit exceeded
* Model availability problems
**Wallet Connection Issues**
* Wallet not connected when AI tries to execute
* Transaction signing failures
* Network connectivity problems
**Backend Communication**
* Chat persistence server unreachable
* Message formatting errors
* Authentication failures
**AI Understanding Issues**
* Ambiguous user queries
* Unsupported operations
* Context confusion in long conversations
## Performance Considerations
**Streaming Optimization**: The AI uses streaming responses for better user experience. Ensure your UI handles partial updates smoothly.
**Context Limits**: Long conversations may hit AI context limits. Implement conversation summarization for extended chats.
## API Reference
For detailed API documentation, see:
* [Solana Agent Kit Hooks Reference](/docs/references/modules/solana-agent-kit/hooks)
* [AI Providers Reference](/docs/references/modules/solana-agent-kit/lib)
* [Utils Reference](/docs/references/modules/solana-agent-kit/utils)
***
The Solana Agent Kit module transforms complex blockchain interactions into natural conversations, making Solana accessible to users of all technical levels while providing powerful automation capabilities for advanced users.
# Swap Module
Source: https://docs.solanaappkit.com/docs/modules/swap
Unified token swapping interface with multi-DEX integration for optimal trading on Solana
The Swap Module provides a comprehensive token swapping solution that integrates multiple DEX providers into a unified interface for the Solana blockchain. It automatically finds the best routes and prices across different protocols to maximize trading efficiency.
## Core Features
Integrated support for Jupiter aggregation, Raydium pools, and PumpSwap custom routing
Automatic route optimization to find the best prices and lowest fees across all DEXs
Live price updates, slippage calculations, and fee estimates for informed trading decisions
Customizable slippage, provider selection, and transaction parameters for power users
## Installation & Setup
Import the swap components and hooks:
```typescript
import {
SwapScreen,
useSwapLogic,
TradeService,
SelectTokenModal
} from '@/modules/swap';
```
Ensure Embedded Wallets are configured:
```typescript
import { useWallet } from '@/modules/wallet-providers';
```
Configure DEX provider settings (optional):
```typescript
const swapConfig = {
defaultProvider: 'jupiter',
slippageTolerance: 0.5,
enableCustomPools: true
};
```
## Module Architecture
The swap module is built with a modular, provider-agnostic architecture:
```
src/modules/swap/
├── components/ # UI components
│ ├── SwapScreen.tsx # Main swap interface
│ ├── SelectTokenModal.tsx
│ ├── SwapComponents/ # Specialized components
│ │ ├── Shimmer.tsx
│ │ ├── ProviderSelector.tsx
│ │ ├── PumpSwapControls.tsx
│ │ ├── SwapInfo.tsx
│ │ ├── StatusDisplay.tsx
│ │ └── Keypad.tsx
├── hooks/ # Custom React hooks
│ └── useSwapLogic.ts
├── services/ # DEX integrations
│ ├── TradeService.ts
│ └── JupiterService.ts
└── index.ts # Public API exports
```
## DEX Providers
**Primary DEX Aggregator** - Best price discovery across all Solana DEXs
```typescript
import { JupiterService } from '@/modules/swap';
// Get optimal swap quote
const quote = await JupiterService.getQuote({
inputMint: 'So11111111111111111111111111111111111111112', // SOL
outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
amount: 1000000000, // 1 SOL in lamports
slippageBps: 50 // 0.5% slippage
});
// Execute swap with Jupiter
const result = await JupiterService.executeSwap({
quote,
userPublicKey: wallet.publicKey,
sendTransaction
});
```
**Features:**
* Route optimization across 20+ DEXs
* Price impact calculation
* Multi-hop swaps
* Minimal slippage
* Best execution prices
**Direct Pool Access** - Concentrated liquidity and direct pool swaps
```typescript
// Raydium integration through Jupiter or direct calls
const raydiumSwap = await TradeService.executeSwap(
inputToken,
outputToken,
amount,
userPublicKey,
sendTransaction,
{ provider: 'raydium' }
);
```
**Features:**
* Concentrated liquidity pools
* Direct pool swaps
* Fee sharing options
* Advanced pool analytics
* Custom liquidity provision
**Custom Pool Support** - Direct pool address specification with custom slippage
```typescript
// PumpSwap with custom pool
const pumpSwapResult = await TradeService.executeSwap(
inputToken,
outputToken,
amount,
userPublicKey,
sendTransaction,
{
provider: 'pumpswap',
poolAddress: 'custom_pool_address',
slippageBps: 300 // 3% slippage
}
);
```
**Features:**
* Custom pool address input
* Configurable slippage (1-30%)
* High impact warnings
* Direct pool interaction
* Specialized token support
## Core Components
**`SwapScreen`** - Complete swap interface with all features
```typescript
import { SwapScreen } from '@/modules/swap';
function TradingInterface() {
return (
);
}
```
**Features:**
* Token selection with search
* Real-time price updates
* Provider selection interface
* Slippage controls
* Transaction status tracking
* Error handling and recovery
**`SelectTokenModal`** - Advanced token selection interface
```typescript
import { SelectTokenModal } from '@/modules/swap';
function CustomTokenSelector() {
const [showModal, setShowModal] = useState(false);
return (
setShowModal(true)} />
setShowModal(false)}
onTokenSelect={(token) => {
setSelectedToken(token);
setShowModal(false);
}}
showPopularTokens={true}
enableSearch={true}
showBalances={true}
/>
);
}
```
**Features:**
* Search functionality with metadata
* Popular tokens list
* Real-time balance display
* Price information
* Custom token import
* Favorite tokens management
**Granular UI Components** - Building blocks for custom interfaces
```typescript
import {
ProviderSelector,
SwapInfo,
StatusDisplay,
Keypad
} from '@/modules/swap/components/SwapComponents';
function CustomSwapInterface() {
return (
);
}
```
## Core Hook: useSwapLogic
The primary hook for swap functionality:
```typescript
import { useSwapLogic } from '@/modules/swap';
import { useWallet } from '@/modules/wallet-providers';
function CustomSwapImplementation() {
const { publicKey, connected, sendTransaction } = useWallet();
const routeParams = useRoute().params || {};
const {
// Token state
inputToken,
outputToken,
setInputToken,
setOutputToken,
// Amount and pricing
inputAmount,
setInputAmount,
outputAmount,
exchangeRate,
priceImpact,
// Transaction state
isLoading,
transactionStatus,
error,
// Actions
handleSwap,
handleTokenSwitch,
refreshPrices,
// Provider state
selectedProvider,
setSelectedProvider,
availableProviders,
// Advanced options
slippage,
setSlippage,
customPoolAddress,
setCustomPoolAddress
} = useSwapLogic(routeParams, publicKey, connected, sendTransaction);
return (
);
}
```
## TradeService Integration
Provider-agnostic service for executing swaps:
```typescript
import { TradeService } from '@/modules/swap';
// Simple swap execution
const swapResult = await TradeService.executeSwap(
inputToken, // Token mint address or symbol
outputToken, // Token mint address or symbol
amount, // Amount in token's base units
walletPublicKey, // User's wallet public key
sendTransaction // Wallet's send transaction function
);
console.log('Swap completed:', swapResult);
// {
// signature: 'transaction_signature',
// inputAmount: 1000000000,
// outputAmount: 995000000,
// provider: 'jupiter',
// priceImpact: 0.12,
// fees: { total: 5000, breakdown: {...} }
// }
```
```typescript
// Advanced swap with custom options
const advancedSwap = await TradeService.executeSwap(
inputToken,
outputToken,
amount,
walletPublicKey,
sendTransaction,
{
// Provider selection
provider: 'jupiter', // 'jupiter', 'raydium', 'pumpswap'
// Slippage control
slippageBps: 100, // 1% slippage
// PumpSwap specific
poolAddress: 'custom_pool_address',
// Fee configuration
priorityFee: 0.001,
// Status callbacks
onStatusUpdate: (status) => {
console.log('Swap status:', status);
},
// Error handling
onError: (error) => {
console.error('Swap error:', error);
}
}
);
```
```typescript
// Calculate fees before execution
const feeEstimate = await TradeService.calculateFees(
inputToken,
outputToken,
amount,
selectedProvider
);
console.log('Fee breakdown:', feeEstimate);
// {
// platformFee: 1000000,
// networkFee: 5000,
// providerFee: 2000,
// total: 1007000,
// totalInSOL: 0.001007
// }
```
## Quick Start Examples
```typescript Basic Swap Interface
import { SwapScreen } from '@/modules/swap';
import { useWallet } from '@/modules/wallet-providers';
function BasicTradingApp() {
const { connected } = useWallet();
if (!connected) {
return (
Connect Wallet to Trade
);
}
return (
Token Swap
);
}
```
```typescript Custom Swap Implementation
import { useSwapLogic } from '@/modules/swap';
import { useWallet } from '@/modules/wallet-providers';
function CustomSwapInterface() {
const { publicKey, connected, sendTransaction } = useWallet();
const {
inputToken,
outputToken,
inputAmount,
outputAmount,
handleSwap,
isLoading,
error,
setInputToken,
setOutputToken,
setInputAmount
} = useSwapLogic({}, publicKey, connected, sendTransaction);
return (
⇅
≈ {outputAmount} {outputToken?.symbol}
{error && (
{error}
)}
);
}
```
```typescript Advanced Trading Dashboard
import {
SwapScreen,
TradeService,
useSwapLogic
} from '@/modules/swap';
import { useFetchTokens } from '@/modules/data-module';
function TradingDashboard() {
const { wallet } = useWallet();
const { tokens, refetch } = useFetchTokens(wallet?.address);
const [tradingHistory, setTradingHistory] = useState([]);
const [favorites, setFavorites] = useState(['SOL', 'USDC', 'BONK']);
const handleSwapComplete = async (result) => {
// Add to trading history
setTradingHistory(prev => [result, ...prev.slice(0, 9)]);
// Refresh portfolio
await refetch();
// Show success notification
Alert.alert(
'Swap Successful!',
`Swapped ${result.inputAmount} ${result.inputToken} for ${result.outputAmount} ${result.outputToken}`
);
};
const getTopTokenPairs = () => {
return [
{ input: 'SOL', output: 'USDC' },
{ input: 'SOL', output: 'BONK' },
{ input: 'USDC', output: 'SOL' },
{ input: 'BONK', output: 'SOL' }
];
};
return (
Trading DashboardPortfolio Value
${tokens?.reduce((sum, token) => sum + (token.value || 0), 0).toFixed(2)}
Quick Swaps
{getTopTokenPairs().map((pair, index) => (
navigateToSwap(pair)}
>
{pair.input} → {pair.output}
))}
Recent Trades
{tradingHistory.map((trade, index) => (
))}
);
}
```
## Advanced Features
### Real-time Price Monitoring
```typescript
function useRealTimePricing(inputToken, outputToken, amount) {
const [quote, setQuote] = useState(null);
const [priceHistory, setPriceHistory] = useState([]);
useEffect(() => {
if (!inputToken || !outputToken || !amount) return;
const fetchQuote = async () => {
try {
const newQuote = await TradeService.getQuote(inputToken, outputToken, amount);
setQuote(newQuote);
// Track price history
setPriceHistory(prev => [
...prev.slice(-29), // Keep last 30 prices
{
timestamp: Date.now(),
rate: newQuote.rate,
priceImpact: newQuote.priceImpact
}
]);
} catch (error) {
console.error('Quote fetch failed:', error);
}
};
// Initial fetch
fetchQuote();
// Update every 10 seconds
const interval = setInterval(fetchQuote, 10000);
return () => clearInterval(interval);
}, [inputToken, outputToken, amount]);
return { quote, priceHistory };
}
```
### Slippage Protection
```typescript
function useSlippageProtection() {
const [slippageSettings, setSlippageSettings] = useState({
auto: true,
custom: 0.5,
maxImpact: 5.0
});
const calculateOptimalSlippage = (priceImpact, volatility) => {
if (priceImpact < 0.1) return 0.1;
if (priceImpact < 0.5) return 0.3;
if (priceImpact < 1.0) return 0.5;
if (priceImpact < 3.0) return 1.0;
return Math.min(priceImpact * 1.5, 5.0);
};
const validateSlippage = (quote, slippage) => {
if (quote.priceImpact > slippageSettings.maxImpact) {
throw new Error(`Price impact (${quote.priceImpact}%) exceeds maximum allowed (${slippageSettings.maxImpact}%)`);
}
if (slippage < quote.priceImpact) {
console.warn('Slippage tolerance may be too low for current market conditions');
}
return true;
};
return {
slippageSettings,
setSlippageSettings,
calculateOptimalSlippage,
validateSlippage
};
}
```
### Multi-Route Comparison
```typescript
function useMultiRouteComparison(inputToken, outputToken, amount) {
const [routes, setRoutes] = useState({});
const [bestRoute, setBestRoute] = useState(null);
useEffect(() => {
if (!inputToken || !outputToken || !amount) return;
const compareRoutes = async () => {
try {
const [jupiterQuote, raydiumQuote, pumpQuote] = await Promise.allSettled([
TradeService.getQuote(inputToken, outputToken, amount, { provider: 'jupiter' }),
TradeService.getQuote(inputToken, outputToken, amount, { provider: 'raydium' }),
TradeService.getQuote(inputToken, outputToken, amount, { provider: 'pumpswap' })
]);
const routeResults = {
jupiter: jupiterQuote.status === 'fulfilled' ? jupiterQuote.value : null,
raydium: raydiumQuote.status === 'fulfilled' ? raydiumQuote.value : null,
pumpswap: pumpQuote.status === 'fulfilled' ? pumpQuote.value : null
};
setRoutes(routeResults);
// Find best route by output amount
const best = Object.entries(routeResults)
.filter(([_, quote]) => quote !== null)
.reduce((best, [provider, quote]) =>
!best || quote.outputAmount > best.quote.outputAmount
? { provider, quote }
: best
, null);
setBestRoute(best);
} catch (error) {
console.error('Route comparison failed:', error);
}
};
compareRoutes();
}, [inputToken, outputToken, amount]);
return { routes, bestRoute };
}
```
## Error Handling & Recovery
**Insufficient Balance**
* Check user's token balance before swap
* Account for transaction fees
* Provide clear balance information
**Slippage Exceeded**
* Automatic slippage adjustment
* Market volatility warnings
* Retry with higher slippage options
**Network Issues**
* RPC connection failures
* Transaction timeout handling
* Automatic retry mechanisms
**Provider Unavailability**
* Fallback to alternative DEXs
* Provider health monitoring
* User notification of issues
```typescript
function RobustSwapExecution() {
const executeSwapWithRetry = async (swapParams, maxRetries = 3) => {
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await TradeService.executeSwap(...swapParams);
} catch (error) {
lastError = error;
console.warn(`Swap attempt ${attempt} failed:`, error.message);
if (attempt === maxRetries) break;
// Handle specific errors
if (error.message.includes('slippage')) {
// Increase slippage and retry
swapParams[5] = {
...swapParams[5],
slippageBps: (swapParams[5]?.slippageBps || 50) * 1.5
};
} else if (error.message.includes('network')) {
// Wait before retry for network issues
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
throw lastError;
};
return { executeSwapWithRetry };
}
```
## Performance Optimization
**Quote Caching**: Implement intelligent quote caching to reduce API calls and improve response times.
**Rate Limiting**: Be mindful of DEX API rate limits when implementing real-time price updates.
```typescript
function useOptimizedQuoting() {
const [quoteCache, setQuoteCache] = useState(new Map());
const [lastQuoteTime, setLastQuoteTime] = useState(0);
const getCachedQuote = (inputToken, outputToken, amount) => {
const key = `${inputToken}-${outputToken}-${amount}`;
const cached = quoteCache.get(key);
if (cached && Date.now() - cached.timestamp < 10000) { // 10 second cache
return cached.quote;
}
return null;
};
const fetchQuoteWithCache = async (inputToken, outputToken, amount) => {
// Check cache first
const cached = getCachedQuote(inputToken, outputToken, amount);
if (cached) return cached;
// Rate limiting
const now = Date.now();
if (now - lastQuoteTime < 1000) { // 1 second minimum between requests
await new Promise(resolve => setTimeout(resolve, 1000 - (now - lastQuoteTime)));
}
const quote = await TradeService.getQuote(inputToken, outputToken, amount);
// Cache result
const key = `${inputToken}-${outputToken}-${amount}`;
setQuoteCache(prev => new Map(prev.set(key, {
quote,
timestamp: Date.now()
})));
setLastQuoteTime(Date.now());
return quote;
};
return { fetchQuoteWithCache };
}
```
## Integration with Other Modules
Essential for transaction signing and balance checking
Token metadata, prices, and portfolio integration
Works alongside Pump.fun, Raydium, and Meteora modules
AI can execute swaps through natural language commands
## API Reference
For detailed API documentation, see:
* [Swap Components Reference](/docs/references/modules/swap/components)
* [Services Reference](/docs/references/modules/swap/services)
* [Hooks Reference](/docs/references/modules/swap/hooks)
***
The Swap Module provides the foundation for all token trading activities in your Solana app, offering users the best possible prices through intelligent multi-DEX routing while maintaining a simple and intuitive interface.
# TokenMill Module
Source: https://docs.solanaappkit.com/docs/modules/tokenmill
Comprehensive token creation and lifecycle management with advanced bonding curves, staking, and vesting capabilities
The TokenMill module provides a complete suite of tools for professional token creation and lifecycle management on Solana. It offers advanced bonding curve configurations, comprehensive market management, and sophisticated tokenomics features including staking and vesting.
## Core Features
Create new token markets with customizable parameters, metadata, and distribution settings
Advanced curve configuration with multiple types: linear, power, exponential, and logarithmic
Complete trading suite with buy/sell functionality, real-time pricing, and slippage protection
Sophisticated staking rewards and flexible vesting schedules for long-term token distribution
## Installation & Setup
Import the components and services you need:
```typescript
import {
TokenMillScreen,
MarketCreationCard,
BondingCurveConfigurator,
createMarket,
setBondingCurve
} from '@/modules/token-mill';
```
Configure TokenMill settings in `.env.local`:
```bash
TOKEN_MILL_CONFIG_PDA=your_config_pda
TOKEN_MILL_PROGRAMID=your_program_id
```
Ensure wallet providers are configured:
```typescript
import { useWallet } from '@/modules/wallet-providers';
```
**Advanced Tokenomics**: TokenMill is designed for sophisticated token engineering. Review the [TokenMill Functions](/docs/functions/tokenmill) documentation for detailed API information.
## Module Architecture
The TokenMill module is structured around professional token lifecycle management:
```
src/modules/token-mill/
├── components/ # UI components for token operations
│ ├── MarketCreationCard.tsx
│ ├── BondingCurveCard.tsx
│ ├── BondingCurveConfigurator.tsx
│ ├── SwapCard.tsx
│ ├── StakingCard.tsx
│ ├── VestingCard.tsx
│ └── FundMarketCard.tsx
├── screens/ # Complete screen implementations
├── services/ # TokenMill service integration
└── types/ # TypeScript definitions
```
## Core Components
**`MarketCreationCard`** - Professional token market creation interface
```typescript
import { MarketCreationCard } from '@/modules/token-mill';
import { useWallet, useConnection } from '@/modules/wallet-providers';
function TokenCreationInterface() {
const { publicKey, wallet } = useWallet();
const { connection } = useConnection();
const [loading, setLoading] = useState(false);
const handleMarketCreated = (marketData) => {
console.log('New market created:', marketData);
// Handle success (navigation, notifications, etc.)
};
return (
);
}
```
**Features:**
* Token metadata configuration (name, symbol, URI)
* Total supply and distribution settings
* Creator and staking fee configuration
* Real-time validation and preview
* Integrated metadata upload
**`BondingCurveConfigurator`** - Advanced curve design interface
```typescript
import { BondingCurveConfigurator } from '@/modules/token-mill';
function CurveDesignInterface() {
const [curveConfig, setCurveConfig] = useState({
type: 'power',
basePrice: 0.001,
topPrice: 1.0,
points: 100,
feePercentage: 2.0,
powerFactor: 2.0
});
const handleCurveChange = (pricePoints, parameters) => {
console.log('Curve updated:', { pricePoints, parameters });
setCurveConfig(parameters);
};
return (
);
}
```
**Curve Types:**
* **Linear**: Constant price increase
* **Power**: Exponential growth with configurable power
* **Exponential**: Natural exponential curve
* **Logarithmic**: Diminishing returns curve
**Features:**
* Real-time curve visualization
* Interactive price point editing
* Parameter validation
* Visual feedback for changes
* Export curve data for analysis
**`SwapCard`** - Professional token trading interface
```typescript
import { SwapCard } from '@/modules/token-mill';
function TokenTradingInterface() {
const [selectedMarket, setSelectedMarket] = useState(null);
const handleSwapComplete = (result) => {
console.log('Swap completed:', result);
// Update portfolio, show confirmation, etc.
};
return (
);
}
```
**Features:**
* Buy tokens using SOL
* Sell tokens for SOL
* Real-time price calculations
* Slippage protection
* Price impact visualization
* Transaction cost estimation
**`StakingCard`** & **`VestingCard`** - Advanced token distribution
```typescript
import { StakingCard, VestingCard } from '@/modules/token-mill';
function TokenDistributionInterface() {
const handleStakingComplete = (result) => {
console.log('Staking operation:', result);
};
const handleVestingComplete = (result) => {
console.log('Vesting operation:', result);
};
return (
);
}
```
**Staking Features:**
* Configurable staking periods
* Dynamic reward rates
* Compound interest options
* Early withdrawal penalties
**Vesting Features:**
* Flexible vesting schedules
* Multiple beneficiaries
* Cliff periods
* Linear and step-based release
## TokenMill Service Integration
For detailed service functions, see the [TokenMill Functions documentation](/docs/functions/tokenmill). Here's a quick overview:
```typescript
import { createMarket, fundMarket } from '@/modules/token-mill';
// Create professional token market
const market = await createMarket({
tokenName: 'Professional Token',
tokenSymbol: 'PROF',
metadataUri: 'https://metadata.example.com/prof.json',
totalSupply: 10_000_000,
creatorFee: 2.5,
stakingFee: 1.0,
userPublicKey: publicKey,
connection,
solanaWallet: wallet,
onStatusUpdate: (status) => {
console.log('Creation status:', status);
}
});
// Fund market with initial liquidity
await fundMarket({
marketAddress: market.address,
amount: 100, // SOL
userPublicKey: publicKey,
connection,
solanaWallet: wallet
});
```
```typescript
import { setBondingCurve } from '@/modules/token-mill';
// Configure advanced bonding curve
await setBondingCurve({
marketAddress: marketAddress,
askPrices: generateCurvePrices('power', {
basePrice: 0.001,
topPrice: 1.0,
points: 100,
powerFactor: 2.0
}),
bidPrices: generateCurvePrices('power', {
basePrice: 0.0009, // Slight spread
topPrice: 0.99,
points: 100,
powerFactor: 2.0
}),
userPublicKey: publicKey,
connection,
solanaWallet: wallet
});
```
```typescript
import { swapTokens, stakeTokens, createVesting } from '@/modules/token-mill';
// Execute token swap
const swapResult = await swapTokens({
marketAddress,
amount: 1000,
direction: 'buy', // or 'sell'
slippage: 0.5,
userPublicKey: publicKey,
connection,
solanaWallet: wallet
});
// Stake tokens for rewards
const stakeResult = await stakeTokens({
tokenAddress,
amount: 5000,
stakingPeriod: 90, // days
userPublicKey: publicKey,
connection,
solanaWallet: wallet
});
// Create vesting schedule
const vestingResult = await createVesting({
tokenAddress,
beneficiary: beneficiaryPublicKey,
totalAmount: 100000,
vestingPeriod: 365, // days
cliffPeriod: 90, // days
userPublicKey: publicKey,
connection,
solanaWallet: wallet
});
```
## Quick Start Examples
```typescript Complete Token Launch Platform
import { TokenMillScreen } from '@/modules/token-mill';
import { useWallet } from '@/modules/wallet-providers';
function TokenLaunchPlatform() {
const { connected, publicKey, wallet } = useWallet();
if (!connected) {
return (
Professional Token Creation
Connect your wallet to access advanced token engineering tools
);
}
return (
TokenMill Platform
Create, manage, and optimize professional-grade tokens
);
}
```
```typescript Custom Market Creation
import { MarketCreationCard, BondingCurveConfigurator } from '@/modules/token-mill';
function CustomTokenCreation() {
const { publicKey, wallet } = useWallet();
const { connection } = useConnection();
const [step, setStep] = useState(1);
const [marketData, setMarketData] = useState(null);
const [curveConfig, setCurveConfig] = useState(null);
const handleMarketCreated = (market) => {
setMarketData(market);
setStep(2);
};
const handleCurveConfigured = async (pricePoints, parameters) => {
try {
await setBondingCurve({
marketAddress: marketData.address,
askPrices: pricePoints.ask,
bidPrices: pricePoints.bid,
userPublicKey: publicKey,
connection,
solanaWallet: wallet
});
Alert.alert(
'Token Launch Complete!',
`${marketData.name} is now live with custom bonding curve`
);
} catch (error) {
Alert.alert('Configuration Failed', error.message);
}
};
return (
{step === 1 ? (
Step 1: Create Market
) : (
Step 2: Configure Bonding Curve
)}
);
}
```
```typescript Advanced Trading Dashboard
import {
SwapCard,
StakingCard,
BondingCurveCard
} from '@/modules/token-mill';
function AdvancedTradingDashboard() {
const [selectedMarket, setSelectedMarket] = useState(null);
const [activeTab, setActiveTab] = useState('trade');
const [portfolio, setPortfolio] = useState([]);
const refreshPortfolio = async () => {
// Refresh user's token holdings and staking positions
const holdings = await fetchUserHoldings(publicKey);
setPortfolio(holdings);
};
return (
TokenMill Trading
{['trade', 'stake', 'curve'].map((tab) => (
setActiveTab(tab)}
>
{tab.charAt(0).toUpperCase() + tab.slice(1)}
))}
{activeTab === 'trade' && (
)}
{activeTab === 'stake' && (
)}
{activeTab === 'curve' && (
)}
);
}
```
## Advanced Features
### Curve Visualization and Analysis
```typescript
function useBondingCurveAnalysis(marketAddress) {
const [curveData, setCurveData] = useState(null);
const [analytics, setAnalytics] = useState(null);
useEffect(() => {
if (!marketAddress) return;
const analyzeCurve = async () => {
try {
const curve = await fetchBondingCurve(marketAddress);
setCurveData(curve);
// Calculate curve analytics
const analysis = {
totalLiquidity: calculateTotalLiquidity(curve),
priceVolatility: calculateVolatility(curve.pricePoints),
optimalBuyZone: findOptimalBuyZone(curve),
resistanceLevels: findResistanceLevels(curve),
supportLevels: findSupportLevels(curve)
};
setAnalytics(analysis);
} catch (error) {
console.error('Curve analysis failed:', error);
}
};
analyzeCurve();
}, [marketAddress]);
return { curveData, analytics };
}
```
### Automated Market Making
```typescript
function useAutomatedMarketMaking(marketAddress) {
const [ammStrategy, setAmmStrategy] = useState(null);
const createAMMStrategy = async (config) => {
try {
const strategy = await configureAMM({
marketAddress,
strategy: config.type, // 'conservative', 'balanced', 'aggressive'
parameters: {
liquidityRange: config.liquidityRange,
rebalanceThreshold: config.rebalanceThreshold,
feeCapture: config.feeCapture
}
});
setAmmStrategy(strategy);
return strategy;
} catch (error) {
console.error('AMM strategy creation failed:', error);
throw error;
}
};
const monitorStrategy = async () => {
if (!ammStrategy) return;
const performance = await getAMMPerformance(ammStrategy.id);
if (performance.shouldRebalance) {
await rebalanceAMM(ammStrategy.id);
}
};
return {
ammStrategy,
createAMMStrategy,
monitorStrategy
};
}
```
### Portfolio Optimization
```typescript
function usePortfolioOptimization() {
const optimizeStakingRewards = async (holdings) => {
const optimizations = [];
for (const holding of holdings) {
const analysis = await analyzeStakingOpportunity(holding);
if (analysis.shouldStake) {
optimizations.push({
token: holding.token,
action: 'stake',
amount: analysis.optimalAmount,
period: analysis.optimalPeriod,
expectedReturn: analysis.expectedReturn
});
}
}
return optimizations;
};
const optimizeVestingSchedule = async (distribution) => {
const schedule = calculateOptimalVesting({
totalAmount: distribution.amount,
beneficiaries: distribution.beneficiaries,
timeHorizon: distribution.timeHorizon,
marketConditions: await getMarketConditions()
});
return schedule;
};
return {
optimizeStakingRewards,
optimizeVestingSchedule
};
}
```
## Error Handling & Best Practices
**Market Creation Failures**
* Insufficient SOL for market creation
* Invalid token metadata
* Duplicate token symbols
* Network connectivity issues
**Bonding Curve Configuration**
* Invalid price point sequences
* Curve parameter validation errors
* Mathematical constraint violations
* Price impact too high
**Staking and Vesting Issues**
* Insufficient token balance for staking
* Invalid vesting schedule parameters
* Beneficiary address validation errors
* Time period constraint violations
### Performance Optimization
**Curve Calculations**: Use web workers for heavy bonding curve calculations to avoid blocking the main thread.
**Network Calls**: Minimize RPC calls by batching operations and caching curve data locally.
```typescript
function useOptimizedTokenMill() {
const [curveCache, setCurveCache] = useState(new Map());
const workerRef = useRef(null);
useEffect(() => {
// Initialize web worker for curve calculations
workerRef.current = new Worker(new URL('../workers/curveCalculator.js', import.meta.url));
return () => {
workerRef.current?.terminate();
};
}, []);
const calculateCurveOptimized = useCallback(async (parameters) => {
const cacheKey = JSON.stringify(parameters);
if (curveCache.has(cacheKey)) {
return curveCache.get(cacheKey);
}
return new Promise((resolve) => {
workerRef.current.postMessage({ type: 'CALCULATE_CURVE', parameters });
workerRef.current.onmessage = (event) => {
const result = event.data.result;
setCurveCache(prev => new Map(prev.set(cacheKey, result)));
resolve(result);
};
});
}, [curveCache]);
return { calculateCurveOptimized };
}
```
## Integration with Other Modules
Essential for transaction signing and wallet state management
Real-time token data and portfolio tracking for created tokens
Integration with broader DEX ecosystem for token trading
Social sharing of professional token launches and achievements
## Security Considerations
**Parameter Validation**: Always validate bonding curve parameters to prevent economic exploits or mathematical errors.
**Test Networks**: Use devnet for testing complex tokenomics before mainnet deployment.
## API Reference
For detailed API documentation, see:
* [TokenMill Functions Reference](/docs/functions/tokenmill) - Complete service function documentation
* [TokenMill Components Reference](/docs/references/modules/token-mill/components)
* [Types Reference](/docs/references/modules/token-mill/types)
***
The TokenMill module provides professional-grade token engineering capabilities, enabling the creation of sophisticated tokenomics with advanced bonding curves, automated market making, and comprehensive lifecycle management tools.
# Embedded wallets Module
Source: https://docs.solanaappkit.com/docs/modules/wallet-providers
Unified wallet integration supporting Privy, Dynamic, Turnkey, and Mobile Wallet Adapter with comprehensive transaction management
The Embedded Wallets module provides a comprehensive, unified interface for multiple wallet solutions in React Native Solana applications. It abstracts away the complexity of different Embedded Wallets while maintaining their unique features and security standards.
## Core Features
Unified interface for Privy, Dynamic, Turnkey, and Mobile Wallet Adapter integration
Complete transaction lifecycle management with signing, simulation, and status tracking
Robust authentication flows with social login, biometrics, and institutional-grade security
Simple, consistent APIs that work across all Embedded Wallets with minimal configuration
## Supported Embedded Wallets
**Social Login & Embedded Wallets** - Perfect for mainstream user adoption
```typescript
import { EmbeddedWalletAuth } from '@/modules/wallet-providers';
function PrivyWalletIntegration() {
return (
{
console.log('Privy wallet connected:', wallet.address);
}}
onDisconnect={() => {
console.log('Privy wallet disconnected');
}}
/>
);
}
```
**Features:**
* OAuth authentication (Google, Apple, Twitter, Discord)
* Email/password login with verification
* Phone number authentication
* Custodial and non-custodial wallet options
* Cross-app wallet recovery
* Embedded wallet creation for users without existing wallets
**Advanced Embedded Wallets** - Feature-rich with multi-chain support
```typescript
import { useDynamicWalletLogic } from '@/modules/wallet-providers';
function DynamicWalletIntegration() {
const {
connectWallet,
switchChain,
getBalance,
supportedChains
} = useDynamicWalletLogic();
const handleConnect = async () => {
try {
await connectWallet({
chain: 'solana',
walletBook: 'all', // Show all supported wallets
displayMode: 'modal'
});
} catch (error) {
console.error('Dynamic connection failed:', error);
}
};
return (
Supported chains: {supportedChains.length}
);
}
```
**Features:**
* Multi-chain wallet support (Solana, Ethereum, Polygon, etc.)
* Customizable wallet selection UI
* Advanced authentication flows
* Chain switching capabilities
* Real-time balance tracking
* Wallet book integration with 300+ wallets
**Institutional-Grade Security** - MPC-based wallets for enterprise use
```typescript
import { TurnkeyWalletAuth, useTurnkeyWalletLogic } from '@/modules/wallet-providers';
function TurnkeyWalletIntegration() {
const { createWallet, signTransaction } = useTurnkeyWalletLogic();
return (
{
console.log('Turnkey wallet connected:', wallet);
}}
authMode="passkey" // or "api"
/>
);
}
```
**Features:**
* Multi-Party Computation (MPC) based security
* Hardware Security Module (HSM) integration
* Passkey authentication support
* Custom authentication flows
* Enterprise-grade compliance
* Advanced key management policies
**Native Mobile Integration** - Direct connection to mobile wallets
```typescript
import { MobileWalletAdapter } from '@/modules/wallet-providers';
function MWAIntegration() {
const [availableWallets, setAvailableWallets] = useState([]);
useEffect(() => {
// Detect installed wallets on device
const detectWallets = async () => {
const wallets = await MobileWalletAdapter.getInstalledWallets();
setAvailableWallets(wallets);
};
detectWallets();
}, []);
const connectMobileWallet = async (walletName) => {
try {
await MobileWalletAdapter.connect(walletName);
} catch (error) {
console.error('MWA connection failed:', error);
}
};
return (
Available Mobile Wallets:
{availableWallets.map((wallet) => (
connectMobileWallet(wallet.name)}
style={styles.walletOption}
>
{wallet.name}
))}
);
}
```
**Features:**
* Native Android wallet integration
* QR code connection support
* Deep linking capabilities
* Automatic wallet detection
* Secure transaction signing
* Connection persistence
## Core Hooks
### useWallet - Universal Wallet Interface
The primary hook for wallet interactions across all providers:
```typescript
import { useWallet } from '@/modules/wallet-providers';
function UniversalWalletComponent() {
const {
// Connection state
wallet,
connected,
connecting,
publicKey,
// Provider information
provider,
providerName,
// Transaction functions
sendTransaction,
signTransaction,
signAllTransactions,
signMessage,
// Connection management
connect,
disconnect,
// Utility functions
getBalance,
requestAirdrop, // devnet only
// Error handling
error,
clearError
} = useWallet();
const handleSendTransaction = async (transaction) => {
try {
clearError();
const signature = await sendTransaction(transaction, connection, {
simulate: true,
commitment: 'confirmed',
skipPreflight: false
});
console.log('Transaction sent:', signature);
return signature;
} catch (error) {
console.error('Transaction failed:', error);
throw error;
}
};
if (!connected) {
return (
Connect Your Wallet
);
}
return (
Provider: {providerName}
Address: {publicKey?.toString().slice(0, 8)}...{publicKey?.toString().slice(-8)}
);
}
```
### useAuth - Authentication Management
Unified authentication interface across all providers:
```typescript
import { useAuth } from '@/modules/wallet-providers';
function AuthenticationComponent() {
const {
// Authentication state
isAuthenticated,
user,
loading,
error,
// Authentication actions
login,
logout,
// User management
updateProfile,
linkAccount,
unlinkAccount,
// Session management
refreshSession,
getSession
} = useAuth();
const handleSocialLogin = async (provider) => {
try {
await login({
provider, // 'google', 'apple', 'twitter', etc.
redirectUrl: 'your-app://auth-callback',
scopes: ['email', 'profile']
});
} catch (error) {
console.error('Login failed:', error);
}
};
const handleEmailLogin = async (email, password) => {
try {
await login({
provider: 'email',
email,
password
});
} catch (error) {
console.error('Email login failed:', error);
}
};
if (loading) {
return ;
}
if (!isAuthenticated) {
return (
Sign In
);
}
return (
Welcome, {user?.email || user?.name}!
);
}
```
## Transaction Management
### TransactionService - Comprehensive Transaction Handling
```typescript
import { TransactionService } from '@/modules/wallet-providers';
// Send transaction with full configuration
const sendAdvancedTransaction = async (transaction, options = {}) => {
try {
const result = await TransactionService.sendTransaction(
transaction,
connection,
{
// Simulation options
simulate: true,
simulationCommitment: 'processed',
// Execution options
commitment: 'confirmed',
skipPreflight: false,
maxRetries: 3,
// Fee configuration
priorityFee: 0.001, // SOL
// Callbacks
statusCallback: (status) => {
console.log('Transaction status:', status);
// Update UI with progress
},
confirmationCallback: (signature) => {
console.log('Transaction confirmed:', signature);
TransactionService.showSuccess(signature);
},
errorCallback: (error) => {
console.error('Transaction error:', error);
TransactionService.showError(error.message);
}
}
);
return result;
} catch (error) {
TransactionService.showError('Transaction failed: ' + error.message);
throw error;
}
};
// Batch transaction sending
const sendBatchTransactions = async (transactions) => {
try {
const results = await TransactionService.sendBatch(
transactions,
connection,
{
concurrent: false, // Send sequentially
stopOnError: true,
batchSize: 5
}
);
console.log('Batch completed:', results);
return results;
} catch (error) {
console.error('Batch failed:', error);
throw error;
}
};
```
### Provider Initialization
```typescript
import {
initDynamicClient,
initPrivyClient,
initTurnkeyClient,
getDynamicClient
} from '@/modules/wallet-providers';
// Initialize all providers at app startup
const initializeWalletProviders = async () => {
try {
// Initialize Dynamic
if (process.env.DYNAMIC_ENVIRONMENT_ID) {
await initDynamicClient({
environmentId: process.env.DYNAMIC_ENVIRONMENT_ID,
walletConnectors: ['solana'],
options: {
initialAuthenticationMode: 'connect-only'
}
});
}
// Initialize Privy
if (process.env.PRIVY_APP_ID) {
await initPrivyClient({
appId: process.env.PRIVY_APP_ID,
clientId: process.env.PRIVY_CLIENT_ID,
config: {
loginMethods: ['email', 'google', 'apple'],
appearance: {
theme: 'dark',
accentColor: '#9945FF'
}
}
});
}
// Initialize Turnkey
if (process.env.TURNKEY_ORGANIZATION_ID) {
await initTurnkeyClient({
apiKey: process.env.TURNKEY_API_PUBLIC_KEY,
organizationId: process.env.TURNKEY_ORGANIZATION_ID,
rpId: process.env.TURNKEY_RP_ID,
rpName: process.env.TURNKEY_RP_NAME
});
}
console.log('All wallet providers initialized');
} catch (error) {
console.error('Provider initialization failed:', error);
}
};
```
## Quick Start Examples
```typescript Basic Multi-Wallet Setup
import { WalletProvider, useWallet } from '@/modules/wallet-providers';
function App() {
return (
);
}
function MainApp() {
const { connected, connect, disconnect } = useWallet();
return (
{connected ? (
) : (
)}
);
}
function WalletSelectionScreen() {
const { connect } = useWallet();
const walletOptions = [
{ name: 'Privy', provider: 'privy', icon: '🔐', description: 'Social login' },
{ name: 'Dynamic', provider: 'dynamic', icon: '⚡', description: 'Multi-chain' },
{ name: 'Turnkey', provider: 'turnkey', icon: '🏛️', description: 'Institutional' },
{ name: 'Mobile Wallet', provider: 'mwa', icon: '📱', description: 'Native wallets' }
];
return (
Choose Your Wallet
{walletOptions.map((option) => (
connect(option.provider)}
>
{option.icon}{option.name}{option.description}
))}
);
}
```
```typescript Advanced Transaction Handling
import { useWallet, TransactionService } from '@/modules/wallet-providers';
function AdvancedTransactionComponent() {
const {
wallet,
sendTransaction,
signTransaction,
publicKey
} = useWallet();
const [txHistory, setTxHistory] = useState([]);
const [loading, setLoading] = useState(false);
const executeComplexTransaction = async () => {
if (!wallet || !publicKey) return;
setLoading(true);
try {
// Create a complex transaction
const transaction = new Transaction();
// Add multiple instructions
transaction.add(
SystemProgram.transfer({
fromPubkey: publicKey,
toPubkey: new PublicKey('destination_address'),
lamports: 1000000 // 0.001 SOL
})
);
// Send with advanced options
const signature = await TransactionService.sendTransaction(
transaction,
connection,
{
simulate: true,
commitment: 'confirmed',
priorityFee: 0.001,
statusCallback: (status) => {
console.log('Transaction status:', status);
// Update UI with real-time status
},
confirmationCallback: (sig) => {
// Add to transaction history
setTxHistory(prev => [{
signature: sig,
timestamp: Date.now(),
status: 'confirmed',
type: 'transfer'
}, ...prev]);
TransactionService.showSuccess(sig);
}
}
);
console.log('Transaction sent:', signature);
} catch (error) {
console.error('Transaction failed:', error);
TransactionService.showError(error.message);
} finally {
setLoading(false);
}
};
const signMultipleTransactions = async (transactions) => {
try {
const signedTxs = await wallet.signAllTransactions(transactions);
console.log('All transactions signed:', signedTxs.length);
return signedTxs;
} catch (error) {
console.error('Multi-sign failed:', error);
throw error;
}
};
return (
Transaction History
{txHistory.map((tx, index) => (
))}
);
}
```
```typescript Provider-Specific Features
import {
useAuth,
useDynamicWalletLogic,
useTurnkeyWalletLogic
} from '@/modules/wallet-providers';
function ProviderSpecificFeatures() {
const { user, linkAccount } = useAuth();
const { switchChain, supportedChains } = useDynamicWalletLogic();
const { createSubOrganization } = useTurnkeyWalletLogic();
// Privy-specific: Link additional accounts
const handleLinkSocialAccount = async (provider) => {
try {
await linkAccount({
type: 'oauth',
provider // 'google', 'twitter', 'discord'
});
console.log('Account linked successfully');
} catch (error) {
console.error('Account linking failed:', error);
}
};
// Dynamic-specific: Chain switching
const handleChainSwitch = async (chainId) => {
try {
await switchChain(chainId);
console.log('Switched to chain:', chainId);
} catch (error) {
console.error('Chain switch failed:', error);
}
};
// Turnkey-specific: Create sub-organization
const handleCreateSubOrg = async (orgName) => {
try {
const subOrg = await createSubOrganization({
organizationName: orgName,
rootUsers: [user.id]
});
console.log('Sub-organization created:', subOrg);
} catch (error) {
console.error('Sub-org creation failed:', error);
}
};
return (
Account Management handleLinkSocialAccount('google')}
/>
Chain ManagementSupported chains: {supportedChains.length} handleChainSwitch('eip155:1')}
/>
Organization Management handleCreateSubOrg('My Sub Org')}
/>
);
}
```
## Error Handling & Recovery
**Connection Failures**
* Network connectivity issues
* Provider service unavailability
* User cancellation during connection
* Invalid configuration parameters
**Transaction Errors**
* Insufficient balance for fees
* Transaction simulation failures
* Network congestion and timeouts
* User rejection of transaction signing
**Authentication Issues**
* OAuth provider failures
* Session expiration
* Invalid credentials
* Biometric authentication failures
```typescript
function RobustWalletErrorHandling() {
const { connect, sendTransaction } = useWallet();
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 3;
const connectWithRetry = async (provider) => {
try {
await connect(provider);
setRetryCount(0); // Reset on success
} catch (error) {
console.error('Connection attempt failed:', error);
if (retryCount < maxRetries) {
setRetryCount(prev => prev + 1);
const delay = 1000 * Math.pow(2, retryCount); // Exponential backoff
setTimeout(() => connectWithRetry(provider), delay);
} else {
// Show user-friendly error
Alert.alert(
'Connection Failed',
'Unable to connect to wallet. Please check your internet connection and try again.',
[
{ text: 'OK', onPress: () => setRetryCount(0) }
]
);
}
}
};
const sendTransactionWithFallback = async (transaction) => {
try {
// Try with simulation first
return await sendTransaction(transaction, connection, {
simulate: true,
commitment: 'confirmed'
});
} catch (simulationError) {
// If simulation fails, try without simulation
console.warn('Simulation failed, trying without:', simulationError);
try {
return await sendTransaction(transaction, connection, {
simulate: false,
skipPreflight: true,
commitment: 'confirmed'
});
} catch (executionError) {
// Provide specific error handling based on error type
if (executionError.message.includes('insufficient funds')) {
throw new Error('Insufficient SOL balance for transaction fees');
} else if (executionError.message.includes('blockhash')) {
throw new Error('Transaction expired. Please try again.');
} else {
throw new Error('Transaction failed: ' + executionError.message);
}
}
}
};
return { connectWithRetry, sendTransactionWithFallback };
}
```
## Security Best Practices
**Private Key Security**: Never store or transmit private keys. All providers handle key management securely.
**Transaction Validation**: Always simulate transactions before execution to catch errors early.
```typescript
function SecureWalletOperations() {
const { signMessage, sendTransaction } = useWallet();
const secureSignMessage = async (message) => {
try {
// Always show user what they're signing
const confirmed = await showSigningConfirmation(message);
if (!confirmed) {
throw new Error('User cancelled signing');
}
const signature = await signMessage(new TextEncoder().encode(message));
return signature;
} catch (error) {
console.error('Secure signing failed:', error);
throw error;
}
};
const secureTransactionExecution = async (transaction) => {
try {
// Validate transaction contents
const validation = await validateTransactionSecurity(transaction);
if (!validation.safe) {
throw new Error('Transaction failed security validation: ' + validation.reason);
}
// Show user transaction details
const confirmed = await showTransactionConfirmation(transaction);
if (!confirmed) {
throw new Error('User cancelled transaction');
}
// Execute with monitoring
return await sendTransaction(transaction, connection, {
simulate: true,
commitment: 'confirmed'
});
} catch (error) {
console.error('Secure transaction failed:', error);
throw error;
}
};
return { secureSignMessage, secureTransactionExecution };
}
```
## Performance Optimization
**Provider Lazy Loading**: Load wallet provider SDKs only when needed to reduce initial bundle size.
```typescript
function useOptimizedWalletLoading() {
const [loadedProviders, setLoadedProviders] = useState(new Set());
const lazyLoadProvider = async (provider) => {
if (loadedProviders.has(provider)) {
return;
}
try {
switch (provider) {
case 'privy':
const { initPrivyClient } = await import('@/modules/wallet-providers/services/privy');
await initPrivyClient(privyConfig);
break;
case 'dynamic':
const { initDynamicClient } = await import('@/modules/wallet-providers/services/dynamic');
await initDynamicClient(dynamicConfig);
break;
case 'turnkey':
const { initTurnkeyClient } = await import('@/modules/wallet-providers/services/turnkey');
await initTurnkeyClient(turnkeyConfig);
break;
}
setLoadedProviders(prev => new Set(prev.add(provider)));
} catch (error) {
console.error(`Failed to load ${provider} provider:`, error);
throw error;
}
};
return { lazyLoadProvider, loadedProviders };
}
```
## Integration with Other Modules
Essential for transaction signing across all DeFi operations
Wallet address integration for portfolio and balance tracking
Wallet integration for AI-powered transaction execution
User authentication and wallet-based identity for social features
## API Reference
For detailed API documentation, see:
* [Wallet Functions Reference](/docs/functions/wallet) - Complete wallet function documentation
* [Wallet Components Reference](/docs/references/modules/wallet-providers/components)
* [Services Reference](/docs/references/modules/wallet-providers/services)
* [Types Reference](/docs/references/modules/wallet-providers/types)
***
The Embedded Wallets module serves as the foundation for all blockchain interactions in your Solana application, providing secure, user-friendly wallet integration that scales from mainstream users to institutional clients.
# Repository Structure
Source: https://docs.solanaappkit.com/docs/repo-structure
Comprehensive guide to understanding and navigating the Solana App Kit codebase organization
This document provides a comprehensive overview of how the Solana App Kit codebase is organized. Understanding this structure will help you navigate the project efficiently and know exactly where to make changes for your specific needs.
## Root Directory Overview
```
solana-app-kit/
├── src/ # Mobile app source code
├── server/ # Backend server
├── android/ # Android-specific files
├── ios/ # iOS-specific files
├── docs/ # Documentation
├── scripts/ # Build and utility scripts
├── App.tsx # Main app component
├── package.json # Dependencies and scripts
└── Configuration files # Various config files
```
**Monorepo Structure**: The kit combines mobile app, backend server, and documentation in a single repository for easier development and maintenance
## Mobile App Structure (`src/`)
The mobile application is organized into several key directories, each serving a specific purpose:
**`src/core/`** - Essential app functionality used across multiple screens
```
src/core/
├── chat/ # AI chat integration
├── dev-mode/ # Development tools and debugging
├── profile/ # User profile management
├── shared-ui/ # Reusable UI components
└── thread/ # Social feed and threading
```
**AI chat integration** with Solana blockchain interactions
**Development tools** for debugging and testing
**User profile management** and account settings
**Reusable components** used throughout the application
**Social feed and threading** for community features
**Purpose**: Core features are central to the app's functionality and provide shared capabilities across multiple screens and modules.
**`src/modules/`** - Independent, protocol-specific integrations
```
src/modules/
├── data-module/ # Blockchain data fetching
├── meteora/ # Meteora protocol integration
├── moonpay/ # MoonPay fiat on-ramp
├── nft/ # NFT functionality
├── pump-fun/ # Pump.fun integration
├── raydium/ # Raydium DEX integration
├── solana-agent-kit/ # AI agent integration
├── swap/ # Token swapping
├── token-mill/ # Token creation and management
└── wallet-providers/ # Wallet connection providers
```
**Blockchain data fetching** and market information
**Dynamic Liquidity Markets** integration
**Fiat on-ramp** for purchasing crypto
**NFT functionality** with Tensor integration
**Meme token creation** and trading
**Professional token launching** platform
**AI agent integration** for automated interactions
**Multi-DEX token swapping** with optimal routing
**Advanced token creation** with custom bonding curves
**Multi-provider wallet** connection and management
**Purpose**: Each module encapsulates a specific protocol or feature, making the codebase modular, maintainable, and allowing you to use only what you need.
**`src/screens/`** - React Native screens organized by feature area
```
src/screens/
├── Common/ # Shared screens
│ ├── intro-screen/ # App introduction
│ ├── login-screen/ # Authentication
│ └── launch-modules-screen/ # Feature selection
└── sample-ui/ # Example implementations
├── chat/ # Chat interface examples
└── Threads/ # Social feed examples
```
**Shared across features** - intro, login, and module selection screens
**Example implementations** showing how to use core features and modules
**Purpose**: Screens define the user interface and navigation flow, providing the main entry points for different app features.
**`src/shared/`** - Common utilities and configurations
```
src/shared/
├── config/ # App configuration
├── context/ # React Context providers
├── hooks/ # Custom React hooks
├── mocks/ # Mock data for development
├── navigation/ # Navigation configuration
├── services/ # API and blockchain services
├── state/ # Redux store and state management
├── types/ # TypeScript type definitions
└── utils/ # Utility functions
```
**App settings** and environment configuration
**React Context** providers for global state
**Custom React hooks** for reusable logic
**Navigation setup** and routing configuration
**Redux store** and state management slices
**TypeScript definitions** for type safety
**Purpose**: Shared resources provide common functionality and maintain consistency across the entire application.
**`src/assets/`** - Static resources and design system
```
src/assets/
├── images/ # Image files
├── svgs/ # SVG graphics
├── colors.ts # Color palette
└── typography.ts # Typography system
```
**Static image files** for app branding and UI
**Scalable vector graphics** for icons and illustrations
**Color palette** definitions for consistent theming
**Typography system** for consistent text styling
**Purpose**: Centralized asset management and design system definitions ensure visual consistency.
## Backend Server Structure (`server/`)
The backend server provides essential API endpoints and services:
```
server/
├── src/
│ ├── controllers/ # Request handlers
│ ├── routes/ # API endpoint definitions
│ ├── service/ # Business logic
│ ├── db/ # Database configuration
│ ├── types/ # TypeScript interfaces
│ └── utils/ # Server utilities
├── package.json # Server dependencies
└── .env.example # Environment template
```
**Purpose**: The server handles blockchain operations, data persistence, external API integrations, and provides enhanced functionality for the mobile app.
## Platform-Specific Directories
**`ios/`** - iOS-specific configuration and native code
```
ios/
├── SolanaAppKit/ # Main iOS project
│ ├── Info.plist # iOS app configuration
│ ├── AppDelegate.mm # iOS app delegate
│ └── Images.xcassets/ # iOS app icons and images
├── Podfile # CocoaPods dependencies
└── SolanaAppKit.xcworkspace # Xcode workspace
```
**iOS Development**: Requires macOS and Xcode for building and testing on iOS devices
**`android/`** - Android-specific configuration and native code
```
android/
├── app/
│ ├── src/main/ # Main Android source
│ ├── build.gradle # App-level build configuration
│ └── proguard-rules.pro # Code obfuscation rules
├── gradle/ # Gradle wrapper
└── build.gradle # Project-level build configuration
```
**Android Development**: Works on any platform with Android Studio and Java/Kotlin support
## Configuration Files
Key configuration files in the root directory:
**Main React Native component** and app initialization entry point
**Project dependencies**, scripts, and metadata configuration
**Expo configuration** for builds, deployment, and app settings
**JavaScript compilation** configuration and plugin setup
**Metro bundler** configuration for React Native builds
**TypeScript compiler** configuration and type checking rules
**Environment variables** (not in repo, created during setup)
**Documentation configuration** for this documentation site
## Module Architecture Pattern
Each module follows a consistent, well-defined structure:
```text Module Structure
module-name/
├── components/ # UI components specific to this module
├── hooks/ # Custom hooks for module functionality
├── screens/ # Screens specific to this module
├── services/ # API and blockchain services
├── types/ # TypeScript interfaces
├── utils/ # Utility functions
├── index.ts # Public API exports
└── README.md # Module documentation
```
```typescript Example Module Export
// modules/example-module/index.ts
export { ExampleComponent } from './components/ExampleComponent';
export { useExample } from './hooks/useExample';
export { ExampleScreen } from './screens/ExampleScreen';
export { exampleService } from './services/exampleService';
export type { ExampleType } from './types';
```
This pattern ensures:
**Similar organization** across all modules makes navigation predictable
**Module internals** are contained with clean public interfaces
**Clean public APIs** make modules easy to integrate and reuse
**Easy to understand** and modify with clear separation of concerns
## Data Flow Architecture
Understanding how components connect and data flows through the application:
**Screens** import and use **Components** from modules for UI composition
**Components** use **Hooks** for state management and business logic
**Hooks** call **Services** for API interactions and blockchain operations
**Services** use **Utils** for common operations and data processing
**Everything** uses **Types** for TypeScript type safety and IntelliSense
### Data Flow Diagram
```mermaid
graph TD
A[Screens] --> B[Components]
B --> C[Hooks]
C --> D[Services]
D --> E[Utils]
F[Types] --> A
F --> B
F --> C
F --> D
F --> E
G[Redux Store] --> C
H[Navigation] --> A
I[Config] --> D
```
## Development Workflow
Understanding the structure helps with common development tasks:
1. **Create or extend modules** in `src/modules/` for protocol integrations
2. **Add components** within the relevant module's `components/` directory
3. **Create hooks** for business logic in the module's `hooks/` directory
4. **Update module exports** in `index.ts` to expose new functionality
1. **Modify components** within relevant modules for feature-specific UI
2. **Update shared components** in `src/core/shared-ui/` for common elements
3. **Adjust styles** using the design system in `src/assets/`
4. **Test across platforms** to ensure consistent appearance
1. **Add screens** to `src/screens/` organized by feature area
2. **Update navigation** configuration in `src/shared/navigation/`
3. **Add routing** for deep linking and navigation flows
4. **Test navigation** on both iOS and Android platforms
1. **Extend services** in modules for protocol-specific integrations
2. **Add shared services** in `src/shared/services/` for common APIs
3. **Update types** to include new API response interfaces
4. **Add error handling** and status management
1. **Update Redux slices** in `src/shared/state/` for global state
2. **Add module-specific state** using local hooks when appropriate
3. **Implement persistence** for important user data
4. **Test state synchronization** across components
## Best Practices
**Keep modules loosely coupled** to maintain modularity and testability
**Put common functionality** in `src/shared/` for reusability across modules
**Define interfaces** in module `types/` directories for better developer experience
**Use `index.ts` files** for clean public APIs and easier imports
**Update module READMEs** when making changes to keep docs current
**Write tests** for critical business logic in services and hooks
## Next Steps
Now that you understand the repository structure, explore these guides:
**Learn about the design system** and asset management for consistent UI
**Understand component architecture** and reusable UI patterns
**Configure the app** and understand environment settings
# Server Overview
Source: https://docs.solanaappkit.com/docs/server/overview
Comprehensive backend server for the Solana App Kit, providing token management, social features, real-time messaging, and various API endpoints for interacting with the Solana blockchain.
## Overview
This backend server is built with Express.js and TypeScript, offering a robust API for Solana blockchain interactions, social features, real-time messaging, and comprehensive token management. It serves as the core backend for the Solana App Kit, providing modular, reusable, and easily customizable components for developers.
## Features
* Token creation via TokenMill
* Market creation and management
* Setting bonding curves
* Token swapping (buy/sell)
* Staking and vesting
* Market graduation and funding
* Jupiter DEX swapping
* Raydium swap integration
* Meteora DBC (Dynamic Bonding Curve)
* PumpFun token launches
* Cross-platform swap quotes
* Thread creation and management
* User profiles and authentication
* Follow system and user interactions
* Image upload and management
* User reactions and engagement
* WebSocket-based chat system
* Global chat functionality
* Real-time message delivery
* Chat image support
* Push notifications via Expo
* IPFS integration via Pinata
* Google Cloud Storage
* Image processing and optimization
* Metadata management
* File upload handling
* Turnkey API integration
* Secure wallet management
* Transaction signing
* Admin authentication system
* Multi-signature support
* NFT minting and management
* Metadata handling
* Collection management
* Aura-based interactions
* User reputation management
* Community engagement tracking
## Prerequisites
* **Node.js**: v16 or higher
* **Package Manager**: pnpm (latest version)
* **Database**: PostgreSQL (latest version)
* **Solana Wallet**: With SOL for transactions
* **RPC Endpoint**: Access to Solana RPC (Helius recommended)
* **Google Cloud Storage**: Account with bucket setup
* **Pinata**: Account for IPFS storage
* **Turnkey**: API access for wallet management
* **Expo**: For push notifications
## Quick Start
```bash
git clone https://github.com/SendArcade/solana-app-kit.git
cd solana-app-kit/server
```
```bash
pnpm install
```
```bash
cp .env.example .env
```
Configure all required environment variables in your `.env` file. See the [Configuration](/docs/server/configuration) section for details.
```bash
pnpm dev
```
The server will start on port 8080 (or the port specified in your environment variables) with WebSocket support enabled.
## Architecture Overview
The server follows a modular, service-oriented architecture:
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Controllers │◄──►│ Services │◄──►│ External APIs │
└─────────────────┘ └─────────────────┘ └─────────────────┘
▲ ▲ ▲
│ │ │
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Routes │ │ Utilities │ │ Blockchain │
└─────────────────┘ └─────────────────┘ └─────────────────┘
▲ ▲ ▲
│ │ │
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Express App │◄──►│ Database │ │ WebSockets │
└─────────────────┘ └─────────────────┘ └─────────────────┘
```
## Core Services
**Capabilities:**
* Token creation and market management
* Setting bonding curves for dynamic pricing
* Token swapping with optimal rates
* Staking mechanisms for rewards
* Vesting schedules for token distribution
* Market graduation and funding
**Key Features:**
* Integration with Solana programs
* Real-time price calculations
* Transaction optimization
**Features:**
* Socket.IO integration
* Global chat functionality
* Real-time message delivery
* Connection management
* Transport optimization
**Implementation:**
* Cross-platform compatibility
* Health monitoring
* Debugging endpoints
**IPFS Integration:**
* Metadata storage via Pinata
* Decentralized content hosting
* Gateway management
**Cloud Storage:**
* Google Cloud Storage for images
* Image processing and optimization
* CDN integration
**Turnkey Integration:**
* Secure key management
* Hardware-backed security
* Multi-signature support
**Features:**
* Wallet creation and recovery
* Transaction signing
* Address management
**Push Notifications:**
* Expo integration
* Real-time delivery
* User targeting
**Features:**
* Notification scheduling
* Custom payload support
* Delivery tracking
## API Endpoints Overview
### TokenMill Endpoints
| Endpoint | Method | Description |
| ------------------------ | ------ | ------------------------------ |
| `/api/config` | POST | Create TokenMill configuration |
| `/api/quote-token-badge` | POST | Get token badge quote |
| `/api/markets` | POST | Create token market |
| `/api/free-market` | POST | Free market from restrictions |
| `/api/tokens` | POST | Create new token |
| `/api/swap` | POST | Execute token swap |
| `/api/stake` | POST | Create staking position |
| `/api/vesting` | POST | Create vesting schedule |
### DEX Integration Endpoints
| Endpoint | Method | Description |
| --------------------- | ------- | ----------------------- |
| `/api/jupiter/*` | Various | Jupiter DEX integration |
| `/api/raydium/swap/*` | Various | Raydium swap operations |
| `/api/meteora/*` | Various | Meteora DBC operations |
| `/api/pump-swap/*` | Various | PumpSwap functionality |
### Social & Real-time Features
| Endpoint | Method | Description |
| -------------------- | ------- | ------------------- |
| `/api/thread` | Various | Thread management |
| `/api/profile` | Various | User profiles |
| `/api/chat` | Various | Real-time messaging |
| `/api/notifications` | Various | Push notifications |
For detailed API documentation, see the [API Reference](/docs/server/endpoints/tokenmill) section.
## Security Measures
**Important Security Considerations**
* All transactions require proper signature verification
* Environment variables store sensitive credentials
* Database queries use parameterized statements
* Error messages are sanitized
* CORS configuration for API access
* WebSocket connection validation
## Development Workflow
```bash Development
# Start with auto-reload
pnpm dev
# Run with specific port
PORT=3000 pnpm dev
```
```bash Production Build
# Build for production
pnpm build
# Start production server
pnpm start
```
```bash Database Operations
# Run migrations
pnpm migrate
# Seed database
pnpm seed
```
## Next Steps
Complete setup instructions with detailed environment configuration
Comprehensive API reference with examples and responses
Production deployment guides for various platforms
Real-world examples of client-server integration
***
**Need Help?** Check out our [support channels](/docs/support) or open an issue in the [GitHub repository](https://github.com/SendArcade/solana-app-kit).
# Solana Service
Source: https://docs.solanaappkit.com/docs/server/services/solana
Comprehensive transaction handling service for the Solana blockchain, featuring Jito bundles and priority fee mechanisms for optimized transaction processing.
## Overview
The Solana service provides a unified interface for handling Solana blockchain transactions with support for:
* **Priority Fee Transactions**: Enhanced processing with configurable fee tiers
* **Jito Bundle Transactions**: MEV-protected transactions through Jito's block engine
* **Automated Commission System**: Built-in 0.5% commission handling
* **Mobile Wallet Adapter Support**: Native mobile wallet integration
- Priority fee management (4 tiers)
- Jito bundle support
- SOL and Token transfers
- Mobile Wallet Adapter (MWA)
- Versioned transactions
* Low, Medium, High, Very-High tiers
* Dynamic calculation
* Compute unit optimization
* Real-time tier selection
* MEV-protected transactions
* Bundle submission
* Status tracking
* Block engine communication
* Comprehensive error parsing
* Retry mechanisms
* Confirmation validation
* Status callbacks
## Module Structure
```
src/shared/services/transactions/
├── index.ts # Main exports
├── methods/ # Transaction execution methods
│ ├── sendSOL.ts # SOL transfers
│ ├── sendToken.ts # Token transfers
│ ├── priority.ts # Priority fee transactions
│ └── jito.ts # Jito bundle transactions
├── core/ # Core utilities and configurations
│ ├── types.ts # TypeScript interfaces
│ ├── constants.ts # Configuration constants
│ ├── commission.ts # Commission utilities
│ ├── helpers.ts # Transaction helpers
│ └── errorParser.ts # Error handling
└── README.md # Documentation
```
## Priority Fee System
| Tier | MicroLamports | Use Case |
| ------------- | ------------- | --------------------- |
| **Low** | 1,000 | Standard transactions |
| **Medium** | 10,000 | Normal priority |
| **High** | 100,000 | High priority |
| **Very-High** | 1,000,000 | Critical transactions |
```typescript
export const DEFAULT_FEE_MAPPING: FeeMapping = {
'low': 1_000,
'medium': 10_000,
'high': 100_000,
'very-high': 1_000_000,
};
```
* Compute Unit Limit: 2,000,000 units
* Compute Unit Price: Based on selected tier
* Dynamic Selection: Retrieved from Redux state
## Jito Bundle Integration
| Feature | Description |
| ------------------------ | --------------------------------------------- |
| **Bundle Submission** | Groups transactions for atomic execution |
| **MEV Protection** | Prevents front-running and sandwich attacks |
| **Guaranteed Inclusion** | Higher success rate for critical transactions |
| **Status Tracking** | Real-time bundle monitoring |
| **Block Engine** | Direct integration with Jito's block engine |
```typescript
// Jito Bundle Configuration
export const JITO_BUNDLE_URL = ENDPOINTS.jito?.blockEngine || '';
interface JitoBundleResponse {
jsonrpc: string;
result: string;
id: number;
}
interface JitoBundleConfig {
maxRetries: number;
retryInterval: number;
timeout: number;
}
```
| Scenario | Recommendation |
| --------------------- | ---------------------------------- |
| **High-Value Trades** | Always use Jito bundles |
| **Token Launches** | Bundle multiple setup transactions |
| **Arbitrage** | Protect against frontrunning |
| **Concurrent Txs** | Group related transactions |
## Transaction Methods
### Core Functions
```typescript sendSOL
// Sends SOL with optional commission and priority fees
const signature = await sendSOL({
wallet: connectedWallet,
recipientAddress: 'recipient_address',
amountSol: 0.1,
connection: solanaConnection,
includeCommission: true,
onStatusUpdate: (status) => console.log(status)
});
```
```typescript sendToken
// Sends SPL tokens with automatic account creation
const signature = await sendToken({
wallet: connectedWallet,
recipientAddress: 'recipient_address',
amount: tokenAmount,
mint: tokenMint,
connection: solanaConnection,
includeCommission: true,
onStatusUpdate: (status) => console.log(status)
});
```
```typescript priorityFee
// Executes transactions with configurable priority fees
const signature = await sendTransactionWithPriorityFee({
wallet: connectedWallet,
instructions: transactionInstructions,
connection: solanaConnection,
shouldUsePriorityFee: true,
includeCommission: true,
onStatusUpdate: (status) => console.log(status)
});
```
```typescript jitoBundle
// Executes MEV-protected transactions
const signature = await sendJitoBundleTransaction({
provider: walletProvider,
instructions: transactionInstructions,
walletPublicKey: userPublicKey,
connection: solanaConnection,
onStatusUpdate: (status) => console.log(status)
});
```
### Commission System
The service includes an automated 0.5% commission system for all transactions.
```typescript
// Commission calculation utilities
interface CommissionUtils {
calculateCommissionLamports(transactionLamports: number): number;
createCommissionInstruction(fromPubkey: PublicKey, transactionLamports: number): TransactionInstruction;
calculateTransferAmountAfterCommission(totalLamports: number): {
transferLamports: number;
commissionLamports: number;
};
}
```
### Error Handling & Retries
```typescript
export const TRANSACTION_RETRIES = {
maxAttempts: 6,
interval: 1500,
confirmationAttempts: 3,
confirmationInterval: 1000,
blockhashAttempts: 3,
blockhashInterval: 500,
};
```
Error types include:
* Confirmation failures
* Network issues
* Wallet errors
* Insufficient funds
## Mobile Wallet Adapter Support
```typescript Android
// Android-specific transaction handling
if (Platform.OS === 'android') {
const signature = await sendPriorityTransactionMWA(
connection,
recipientAddress,
lamportsAmount,
feeMapping,
(status) => console.log(status)
);
}
```
## Configuration
### Environment Variables
```bash
# Commission wallet address
COMMISSION_WALLET=your_commission_wallet_address
# Jito configuration
JITO_BUNDLE_URL=https://your-jito-endpoint
# Solana cluster
CLUSTER=mainnet-beta
```
### Redux Integration
```typescript
// Get current settings from Redux state
const transactionMode = getCurrentTransactionMode(); // 'jito' | 'priority'
const feeTier = getCurrentFeeTier(); // 'low' | 'medium' | 'high' | 'very-high'
const feeAmount = getCurrentFeeMicroLamports();
export type TransactionType = 'swap' | 'transfer' | 'stake' | 'nft' | 'token';
export type TransactionMode = 'jito' | 'priority';
```
## Best Practices
Use Jito for MEV-sensitive transactions, Priority fees for speed
Match tier to transaction urgency and importance
Implement comprehensive error handling with status callbacks
Check MWA compatibility for Android devices
***
For detailed API documentation and examples, see the [API Reference](/docs/server/endpoints/solana) section.
# Setup Guide
Source: https://docs.solanaappkit.com/docs/setup
Complete installation and configuration guide for setting up your Solana App Kit development environment
This guide will walk you through setting up your development environment and getting your first Solana mobile app running in minutes.
## Prerequisites
Before you begin, ensure you have the following installed:
Download from [nodejs.org](https://nodejs.org/) - LTS version recommended
**pnpm** (recommended), npm, or pnpm - we recommend pnpm for better performance
Version control system - download from [git-scm.com](https://git-scm.com/)
**macOS Required**: iOS development requires a Mac computer
**Latest version from Mac App Store** - includes iOS Simulator and build tools
Install with: `sudo gem install cocoapods`
**Included with Xcode** - for testing on virtual devices
**With Android SDK** - download from [developer.android.com](https://developer.android.com/studio)
**Or physical Android device** - for testing your applications
**Version 11 or newer** - required for Android builds
Install globally: `npm install -g @expo/cli`
For building and deployment: `npm install -g eas-cli`
## Quick Start
The fastest way to get started is using our CLI tool:
```bash
npx start-solana-app
```
This command will automatically:
* Clone the repository
* Install all dependencies
* Set up environment variables
* Launch the development server
Your app will be running on iOS Simulator, Android Emulator!
**That's it!** Most developers can skip the manual installation section below.
## Manual Installation
If you prefer to set up manually or need more control:
```bash
git clone https://github.com/SendArcade/solana-app-kit.git
cd solana-app-kit
```
```bash pnpm (Recommended)
pnpm install
```
```bash npm
npm install
```
```bash pnpm
pnpm install
```
```bash
cd ios
pod install
cd ..
```
## Environment Configuration
The app requires several environment variables for full functionality:
```bash
cp .env.example .env.local
```
Add your API keys and configuration to `.env.local`:
```env
# Blockchain Configuration
CLUSTER=mainnet-beta
RPC_URL=https://api.mainnet-beta.solana.com
# Wallet Providers
PRIVY_APP_ID=your_privy_app_id
PRIVY_CLIENT_ID=your_privy_client_id
DYNAMIC_ENVIRONMENT_ID=your_dynamic_env_id
DYNAMIC_API_KEY=your_dynamic_api_key
# Turnkey Wallet Configuration
TURNKEY_BASE_URL=https://api.turnkey.com
TURNKEY_RP_ID=host.exp.exponent
TURNKEY_RP_NAME=your_app_name
TURNKEY_ORGANIZATION_ID=your_turnkey_organization_id
TURNKEY_API_PUBLIC_KEY=your_turnkey_public_key
TURNKEY_API_PRIVATE_KEY=your_turnkey_private_key
# API Services
HELIUS_API_KEY=your_helius_api_key
TENSOR_API_KEY=your_tensor_api_key
COINGECKO_API_KEY=your_coingecko_api_key
BIRDEYE_API_KEY=your_birdeye_api_key
OPENAI_API_KEY=your_openai_api_key
# Backend Server
SERVER_URL=http://localhost:3000
```
## Getting API Keys
**Essential for core functionality:**
**Enhanced Solana RPC** - Sign up for better reliability and faster responses
**Embedded Wallets** - Get credentials for social login and wallet creation
**For enhanced features:**
**Multi-chain Wallets** - Register for 300+ wallet support
**Enterprise Wallets** - Apply for institutional-grade security
**NFT Data** - Get API access for NFT marketplace features
**Market Data** - Free API for token prices and market info
**Token Analytics** - Sign up for advanced token data
**AI Features** - Get API key for AI-powered interactions
## Backend Server Setup
The kit includes a powerful backend server for enhanced functionality:
```bash
cd server
```
```bash
pnpm install
```
```bash
cp .env.example .env
```
```bash
# Create database
createdb solana_app_kit
# Run migrations
pnpm run migrate
```
```bash
pnpm dev
```
Server will be available at `http://localhost:3000`
```env
# Blockchain
WALLET_PRIVATE_KEY=your_wallet_private_key
RPC_URL=your_helius_rpc_url
TOKEN_MILL_PROGRAMID=your_token_mill_program_id
TOKEN_MILL_CONFIG_PDA=your_token_mill_config_pda
# Database
DATABASE_URL=postgresql://username:password@localhost:5432/solana_app_kit
# IPFS Storage
PINATA_JWT=your_pinata_jwt
PINATA_GATEWAY=your_pinata_gateway
PINATA_SECRET=your_pinata_secret
PINATA_API_KEY=your_pinata_api_key
# Cloud Storage
GCS_BUCKET_NAME=your_gcs_bucket_name
SERVICE_ACCOUNT_EMAIL=your_service_account_email
# Supabase (optional)
SUPABASE_URL=your_supabase_url
SUPABASE_ANON_KEY=your_supabase_anon_key
```
## Running the Mobile App
From the root directory:
```bash
pnpm start
```
```bash
# Using Expo CLI
pnpm ios
# Or using Expo development build
expo run:ios
```
```bash
# Using Expo CLI
pnpm android
# Or using Expo development build
expo run:android
```
```bash
# Open in web browser
pnpm web
```
### Development Server Commands
When the Expo server is running, use these keyboard shortcuts:
Press **`i`** to open iOS simulator
Press **`a`** to open Android emulator
Press **`w`** to open in web browser
Press **`r`** to reload the app
Press **`m`** to toggle the menu
Press **`d`** to open developer tools
## Verification
✅ You should see the intro screen with wallet connection options
✅ Check `http://localhost:3000/health` returns 200 status
✅ Try connecting with any configured wallet provider
✅ Navigate through the app's main features
## Development Mode
The app includes a special development mode for easier debugging:
1. **Shake your device** or press `Cmd+D` (iOS) / `Cmd+M` (Android)
2. **Select "Dev Mode"** from the developer menu
3. **Access debugging tools** and mock data
| Feature | Description |
| -------------------- | ------------------------------------- |
| **Mock Wallets** | Test without real wallet connections |
| **Sample Data** | Pre-populated data for UI development |
| **Network Logging** | Debug API calls in real-time |
| **State Inspection** | Monitor Redux state changes |
## Troubleshooting
| Issue | Solution |
| --------------------- | ------------------------------------- |
| **Cache Problems** | Run `pnpm start --reset-cache` |
| **Port Conflicts** | Try different port with `--port` flag |
| **Dependency Issues** | Clear node\_modules and reinstall |
```bash
# Reset cache and restart
pnpm start --reset-cache
# or
expo start --clear
```
| Step | Command/Action |
| ------------------- | ------------------------------------- |
| **Update Pods** | `cd ios && pod install --repo-update` |
| **Clear Xcode** | Clean build folder and derived data |
| **Reset Simulator** | Erase all content and settings |
```bash
cd ios
pod install --repo-update
cd ..
```
| Step | Command/Action |
| ---------------- | ------------------------------- |
| **Clean Build** | `cd android && ./gradlew clean` |
| **Update Tools** | Check SDK Manager for updates |
| **Clear Cache** | Clear Android Studio caches |
```bash
cd android
./gradlew clean
cd ..
```
| Check | Description |
| ------------------ | ------------------------------- |
| **File Location** | `.env.local` in root directory |
| **Server Restart** | Required after variable changes |
| **Required Vars** | All necessary variables set |
| **API Keys** | Valid format and permissions |
**Verification Steps:**
1. Check file existence and location
2. Verify variable format and values
3. Restart development server
4. Test API connectivity
**Need Help?** Join our [Telegram community](https://t.me/solanaappkit) for real-time support from developers and maintainers.
## Next Steps
**Navigate through screens** and discover the app's features and capabilities
**Understand the structure** with our comprehensive project organization guide
**Test wallet connections** and explore token swaps, NFTs, and other functionality
**Modify the app** for your specific use case with practical examples
## Production Deployment
Ready to ship your app? Deploy to app stores with EAS Build:
```bash
# Build for iOS
eas build --platform ios --profile production
# Submit to App Store
eas submit --platform ios
```
```bash
# Build for Android
eas build --platform android --profile production
# Submit to Play Store
eas submit --platform android
```
**Learn More**: Check out the [EAS Build documentation](https://docs.expo.dev/build/introduction/) for detailed deployment instructions.
***
# Vibe Coding setup
Source: https://docs.solanaappkit.com/docs/using-llms/cursor-setup
Using Docs in Cursor - Learn how to set up Cursor IDE and MCP with Solana App Kit documentation
# Setting Up LLM Integrations with Solana App Kit
This guide covers two powerful ways to integrate Solana App Kit with LLMs: Cursor IDE integration and Model Context Protocol (MCP) setup.
## Cursor IDE Setup
### Prerequisites
* [Cursor IDE](https://cursor.sh) installed on your machine
* Basic familiarity with Cursor's interface
### Configuration Steps
1. Open Cursor IDE
2. Navigate to **Settings** > **Features** > **Docs**
3. Click on **Add new doc**
4. In the URL field, paste the following URL:
```bash
https://docs.solanaappkit.com/llms-full.txt
```
### Using Solana App Kit Documentation in Cursor
Once configured, you can access Solana App Kit's documentation directly within Cursor using the following methods:
#### Method 1: Using @docs Command
Type `@docs` followed by "Solana App Kit" to reference the documentation in your code. For example:
```typescript
// @docs -> Solana App Kit: How to initialize a wallet connection
```
#### Method 2: Local Docs MCP Setup
You can also ask questions about Solana App Kit directly in comments, and Cursor will use the documentation to provide relevant answers and code suggestions.
## Model Context Protocol (MCP) Setup
### Overview
The Model Context Protocol (MCP) connects Solana App Kit's functions to LLMs and AI applications, enabling AI-powered interactions with the toolkit. With MCP, you can leverage Solana App Kit's documentation and APIs directly in your AI applications.
TLDR :

### Quick Setup
Install the Solana App Kit Docs MCP server using the following command:
```bash
npx mint-mcp add docs.solanaappkit.com
```
### Configuration Steps
1. After running the installation command, you'll be prompted to select which MCP clients to enable
2. Choose the clients that best suit your development needs
3. The terminal will provide you with the final configuration and usage instructions
### Using MCP in Your Project
Once configured, you can use the MCP server to:
* Query Solana App Kit documentation programmatically
* Access API endpoints with AI-powered context
* Get intelligent suggestions based on the documentation
## Benefits
* **Contextual Help**: Get immediate access to Solana App Kit documentation while coding
* **Smart Completions**: Both Cursor and MCP use the documentation context to provide accurate suggestions
* **Faster Development**: Reduce time spent switching between documentation and code
* **AI-Powered Integration**: Leverage LLMs to interact with Solana App Kit more effectively
## Troubleshooting
If you encounter any issues:
1. Verify that all URLs and API keys are correctly entered
2. Ensure necessary permissions are granted for both Cursor and MCP
3. Check your network connection and firewall settings
4. Try refreshing or reinstalling the tools if issues persist
## Next Steps
After setting up both Cursor and MCP:
1. Explore the various modules and features available in Solana App Kit
2. Test the AI-powered documentation queries in your development workflow
3. Start building your Solana application with enhanced AI assistance