Solana AMM SDK Functions
This document outlines the external functions available for users to interact with the Raydium SDK V2 implementation for DEX operations on Solana.
Entry Points Overview
Users interact with the unified Raydium class that provides access to specialized modules:
- Raydium.load(): Main SDK initialization
- CLMM: Concentrated Liquidity Market Maker operations
- CPMM: Constant Product Market Maker with curve calculations
- Liquidity: AMM liquidity pool management (V4/V5)
- TradeV2: Advanced trading and routing
- Farm: Farming/staking operations
- Launchpad: Token launchpad with pricing curves
- Account: Token account management
- Token: Token metadata and information
SDK Initialization
Raydium.load(config:
RaydiumLoadParams
)
Initialize the main SDK instance with connection and configuration.
CLMM Module Functions
Position Management
openPositionFromBase<T>(params:
OpenPositionFromBaseParams
)
Create concentrated liquidity position with base token amounts.
openPositionFromLiquidity<T>(params: OpenPositionFromLiquidityParams)
Create position with specific liquidity amounts.
increasePositionFromBase<T>(params: IncreasePositionFromBaseParams)
Add liquidity to existing position using base amounts.
increasePositionFromLiquidity<T>(params: IncreasePositionFromLiquidityParams)
Add liquidity to existing position using liquidity amounts.
decreaseLiquidity<T>(params:
DecreaseLiquidityParams
)
Remove liquidity from position.
closePosition<T>(params: ClosePositionParams)
Close entire position and burn NFT.
Pool Management
createPool<T>(params:
CreateClmmPoolParams
)
Create new concentrated liquidity pool.
Swapping
swap<T>(params:
ClmmSwapParams
)
Execute token swap through CLMM pool.
swapBaseOut<T>(params: ClmmSwapBaseOutParams)
Execute swap with exact output amount.
Reward Management
initReward<T>(params: InitRewardParams)
Initialize reward pool for position incentives.
setReward<T>(params: SetRewardParams)
Configure reward distribution parameters.
collectReward<T>(params: CollectRewardParams)
Collect accumulated rewards from positions.
harvestAllRewards<T>(params: HarvestAllRewardsParams)
Batch harvest all available rewards.
CPMM Module Functions
Pool Operations
createPool<T>(params:
CreateCpmmPoolParam
)
Create constant product market maker pool.
addLiquidity<T>(params:
AddCpmmLiquidityParams
)
Add liquidity to CPMM pool.
withdrawLiquidity<T>(params: WithdrawCpmmLiquidityParams)
Remove liquidity from CPMM pool.
swap<T>(params:
CpmmSwapParams
)
Execute swap through constant product curve.
LP Token Management
lockLp<T>(params: LockCpmmLpParams)
Lock LP tokens for rewards or time-based restrictions.
harvestLockLp<T>(params: HarvestLockCpmmLpParams)
Harvest rewards from locked LP positions.
Liquidity Module Functions (AMM V4/V5)
Standard AMM Operations
addLiquidity<T>(params:
AddLiquidityParams
)
Add liquidity to standard AMM pools.
removeLiquidity<T>(params:
RemoveParams
)
Remove liquidity from AMM pools.
swap<T>(params: AmmSwapParams)
Execute AMM swap with fixed product curve.
Pool Creation
createPoolV4<T>(params: CreatePoolV4Params)
Create AMM V4 liquidity pool.
createMarketAndPoolV4<T>(params: CreateMarketAndPoolV4Params)
Create market and pool simultaneously.
Migration
removeAllLpAndCreateClmmPosition<T>(params: MigrationParams)
Migrate AMM position to CLMM concentrated liquidity.
TradeV2 Module Functions
Multi-Pool Routing
swap<T>(params:
TradeSwapParams
)
Execute optimal routing swap across multiple pools.
getAllRoute(params:
GetAllRouteParams
)
Find all possible trading routes between token pairs.
getAllRouteComputeAmountOut(params: ComputeAllRoutesParams)
Calculate output amounts for all available routes.
SOL Wrapping
wrapWSol<T>(params:
WrapWSolParams
)
Wrap native SOL to wrapped SOL token.
unWrapWSol<T>(params: UnwrapWSolParams)
Unwrap wrapped SOL back to native SOL.
Farm Module Functions
Farm Pool Management
create<T>(params:
CreateFarmParams
)
Create new farming/staking pool.
deposit<T>(params:
FarmDWParam
)
Stake LP tokens in farm.
withdraw<T>(params:
FarmDWParam
)
Unstake LP tokens from farm.
Reward Management
restartReward<T>(params: RestartRewardParams)
Restart reward distribution for farm pool.
addNewRewardToken<T>(params: AddNewRewardTokenParams)
Add additional reward token to existing farm.
withdrawFarmReward<T>(params: WithdrawFarmRewardParams)
Claim accumulated farming rewards.
harvestAllRewards<T>(params: HarvestAllFarmRewardsParams)
Batch harvest all available farm rewards.
Launchpad Module Functions
Token Launch Management
createLaunchpad<T>(params:
CreateLaunchpadParams
)
Launch new token with pricing curve.
Trading on Curves
buyToken<T>(params:
BuyTokenParams
)
Purchase tokens using curve pricing.
sellToken<T>(params: SellTokenParams)
Sell tokens using curve pricing.
Platform Management
createPlatformConfig<T>(params: CreatePlatformConfigParams)
Configure launchpad platform parameters.
updatePlatformConfig<T>(params: UpdatePlatformConfigParams)
Update platform fee structure and settings.
claimPlatformFee<T>(params: ClaimPlatformFeeParams)
Claim accumulated platform fees.
Vesting
createVesting<T>(params: CreateVestingParams)
Set up token vesting schedule.
claimVesting<T>(params: ClaimVestingParams)
Claim vested tokens according to schedule.
Account Module Functions
Token Account Management
fetchWalletTokenAccounts()
Fetch all token accounts for connected wallet.
getOrCreateTokenAccount(params:
GetOrCreateTokenAccountParams
)
Get existing or create new associated token account.
checkOrCreateAta(params: CheckOrCreateAtaParams)
Check for and create Associated Token Account if needed.
handleTokenAccount(params: HandleTokenAccountParams)
Process multiple token account operations.
Event Listeners
addAccountChangeListener(callback: AccountChangeCallback)
Listen for token account balance changes.
removeAccountChangeListener(listenerId: string)
Remove account change listener.
Token Module Functions
Token Information
load(params?:
TokenLoadParams
)
Load token lists from Jupiter and custom sources.
getTokenInfo(mint: string | PublicKey)
Get comprehensive token metadata and information.
Key Differences from Standard AMM SDKs
1. Environment-Based Program ID Configuration
Purpose: Supports both testnet and mainnet deployments with different program IDs.
Usage:
// Mainnet (default)
const raydium = await Raydium.load({
connection: new Connection(clusterApiUrl("mainnet-beta")),
environment: "mainnet",
});
// Testnet
const raydium = await Raydium.load({
connection: new Connection(clusterApiUrl("mainnet-beta")),
environment: "testnet",
});
2. Multi-Protocol Support
Unified Interface: Single SDK supports:
- CLMM: Concentrated liquidity (Uniswap V3-style)
- CPMM: Constant product with custom curves
- AMM V4/V5: Standard automated market makers
- Cross-Protocol Routing: Optimal routing across all pool types
3. Advanced Transaction Building
Transaction Versioning: Support for both Legacy and V0 transactions:
// V0 transaction (recommended)
const result = await raydium.clmm.swap<TxVersion.V0>({
// params
});
// Legacy transaction
const result = await raydium.clmm.swap<TxVersion.Legacy>({
// params
});
Compute Budget Integration: Built-in compute unit optimization and priority fees.
4. Launchpad Integration with Pricing Curves
Custom Curves: Support for multiple pricing mechanisms:
- Linear: Constant price increase
- Exponential: Exponential price growth
- Power: Power function pricing
- Constant Product: Bonding curve mechanics
5. Comprehensive Reward Systems
Multi-Token Rewards: Support for complex reward structures:
- Position-based rewards (CLMM)
- LP farming rewards (Traditional AMM)
- Time-locked staking rewards
- Platform fee sharing
6. Built-in Account Management
ATA Handling: Automatic Associated Token Account creation and management.
Balance Tracking: Real-time token balance monitoring with change listeners.
Access Control Summary
SDK Owner (Wallet)
Powers:
- Execute all trading and liquidity operations
- Create and manage positions across all protocols
- Participate in farming and launchpad activities
- Manage token accounts and balances
Environment Configuration
Testnet Environment:
- Uses testnet program IDs for CLMM operations
- Suitable for development and testing
Mainnet Environment (default):
- Uses production program IDs
- Real token operations and value
Protocol-Specific Access
CLMM Positions
NFT-Based: Each position represented as NFT with full transferability
Farm Participation
Stake-Based: Access controlled by LP token ownership and staking
Launchpad Access
Token-Based: Participation based on base token holdings and curve mechanics
Error Handling
Common Error Types
EMPTY_CONNECTION
: Connection not providedEMPTY_OWNER
: Wallet/owner not setINSUFFICIENT_BALANCE
: Insufficient token balanceSLIPPAGE_EXCEEDED
: Price moved beyond slippage toleranceINVALID_POOL
: Pool not found or inactive
Transaction Failures
COMPUTE_BUDGET_EXCEEDED
: Transaction requires more compute unitsBLOCKHASH_EXPIRED
: Transaction blockhash expiredSIGNATURE_VERIFICATION_FAILED
: Invalid signature or signing failure
Usage Notes
- Environment Consistency: Ensure consistent environment configuration across all operations
- Connection Management: Maintain stable RPC connection for optimal performance
- Account Pre-funding: Ensure sufficient SOL for transaction fees and rent exemption
- Token Account Creation: SDK handles ATA creation automatically when needed
- Slippage Protection: All swap operations include configurable slippage protection
- Multi-Protocol Routing: TradeV2 automatically routes across optimal liquidity sources
- Real-time Data: Built-in caching with configurable refresh intervals for API data
- Transaction Versioning: V0 transactions recommended for lower fees and better UX
TypeScript Integration
Full Type Safety: Complete TypeScript definitions for all parameters, return types, and configurations.
Generic Transaction Types: Support for both transaction versions with proper typing:
type SwapResult<T extends TxVersion> = T extends TxVersion.V0
? MakeV0Transaction
: MakeTransaction;
Strongly Typed Parameters: All function parameters use TypeScript interfaces with required/optional field validation.
Interface and Type Definitions
SDK Initialization
RaydiumLoadParams
interface RaydiumLoadParams {
connection: Connection;
cluster?: Cluster;
environment?: Environment; // "testnet" | "mainnet"
owner?: PublicKey | Keypair;
apiRequestInterval?: number;
apiRequestTimeout?: number;
signAllTransactions?: SignAllTransactions;
urlConfigs?: API_URL_CONFIG;
jupTokenType?: JupTokenType;
disableFeatureCheck?: boolean;
blockhashCommitment?: Commitment;
}
CLMM Module Interfaces
OpenPositionFromBaseParams
interface OpenPositionFromBaseParams {
poolInfo: ClmmPoolInfo;
tickLower: number;
tickUpper: number;
baseIn: boolean;
baseAmountIn: BN;
}
DecreaseLiquidityParams
interface DecreaseLiquidityParams {
poolInfo: ClmmPoolInfo;
positionInfo: PersonalPositionState;
liquidity: BN;
amountMinA: BN;
amountMinB: BN;
}
CreateClmmPoolParams
interface CreateClmmPoolParams {
mint1: ApiV3Token;
mint2: ApiV3Token;
ammConfig: ClmmConfigInfo;
initialPrice: Decimal;
startTime: BN;
}
ClmmSwapParams
interface ClmmSwapParams {
poolInfo: ClmmPoolInfo;
inputMint: PublicKey;
amountIn: BN;
amountOutMin: BN;
sqrtPriceLimitX64?: BN;
}
CPMM Module Interfaces
CreateCpmmPoolParam
interface CreateCpmmPoolParam {
mint1: ApiV3Token;
mint2: ApiV3Token;
mintAAmount: BN;
mintBAmount: BN;
startTime: BN;
feeConfig?: {
tradeFeeBps: number;
protocolFeeRate: number;
fundFeeRate: number;
};
}
AddCpmmLiquidityParams
interface AddCpmmLiquidityParams {
poolInfo: CpmmRpcData;
inputAmount: BN;
baseIn: boolean;
slippage: number;
}
CpmmSwapParams
interface CpmmSwapParams {
poolInfo: CpmmRpcData;
inputMint: PublicKey;
amountIn: BN;
amountOutMin: BN;
}
Liquidity Module Interfaces
AddLiquidityParams
interface AddLiquidityParams {
poolInfo: AmmRpcData;
inputAmount: BN;
anotherAmount: BN;
fixedSide: "A" | "B";
slippage: number;
}
RemoveParams
interface RemoveParams {
poolInfo: AmmRpcData;
lpAmount: BN;
amountOutA: BN;
amountOutB: BN;
}
TradeV2 Module Interfaces
TradeSwapParams
interface TradeSwapParams {
routeType: "amm" | "clmm" | "cpmm";
inputMint: PublicKey;
outputMint: PublicKey;
amountIn: BN;
amountOutMin: BN;
routes?: RouteInfo[];
}
GetAllRouteParams
interface GetAllRouteParams {
inputMint: PublicKey;
outputMint: PublicKey;
inputAmount: BN;
slippage: number;
}
WrapWSolParams
interface WrapWSolParams {
amount: BN;
}
Farm Module Interfaces
CreateFarmParams
interface CreateFarmParams {
lpMint: PublicKey;
rewardMints: PublicKey[];
rewardPerSecond: BN[];
startTime: BN;
endTime: BN;
}
FarmDWParam
interface FarmDWParam {
farmId: PublicKey;
lpAmount: BN;
}
Launchpad Module Interfaces
CreateLaunchpadParams
interface CreateLaunchpadParams {
mint: PublicKey;
curveType: "linear" | "exponential" | "power" | "constant";
curveConfig: CurveConfig;
startTime: BN;
maxSupply: BN;
}
BuyTokenParams
interface BuyTokenParams {
poolInfo: LaunchpadRpcData;
baseAmountIn: BN;
amountOutMin: BN;
}
Account Module Interfaces
GetOrCreateTokenAccountParams
interface GetOrCreateTokenAccountParams {
mint: PublicKey;
owner?: PublicKey;
notUseTokenAccount?: boolean;
}
Token Module Interfaces
TokenLoadParams
interface TokenLoadParams {
type?: JupTokenType;
forceUpdate?: boolean;
}