Hello π,
In earlier issues, I explained the essential steps for creating a Solana Sniper bot, programming methods, SPL tokens, and more. Additionally, during the coding process, we developed two scripts: one for transferring SOL from Wallet A to Wallet B, and another for transferring SPL tokens between the same wallets.
In this issue, Iβll explore Solana DEX platforms, diving into how they are related to the Solana Sniper bot. Iβll also cover a practical coding example, walking through a script to swap Token A and Token B on the Solana blockchain.
1. Solana DEX
Solana DEXs (Decentralized Exchanges) are platforms built on the Solana blockchain that enable users to trade cryptocurrencies directly with one another without the need for a centralized intermediary.
1.1 Basic DEX concepts
-
Decentralized Exchange (DEX)
- A DEX is a platform that allows users to trade cryptocurrencies directly with one another without relying on a centralized intermediary (like a traditional exchange).
- Trades are executed using smart contracts, and users retain control of their funds through non-custodial wallets.
-
Automated Market Maker (AMM)
- An AMM is a type of DEX that replaces traditional order books with liquidity pools.
- Users (called liquidity providers) deposit pairs of tokens into a pool, and trades are executed against these pools based on a mathematical formula (e.g., x*y=k).
- Examples: Raydium, Orca.
-
Liquidity Pools
- Liquidity pools are collections of funds provided by users to facilitate trading on AMM-based DEXs.
- Each pool consists of two tokens (e.g., SOL/USDC), and the price of the tokens is determined by the ratio of the tokens in the pool.
- Liquidity providers earn fees from trades that occur in their pool.
-
Liquidity Providers (LPs)
- Users who deposit tokens into liquidity pools to enable trading.
- In return, they earn a share of the trading fees generated by the pool.
- LPs are exposed to impermanent loss, which occurs when the price of the tokens in the pool changes significantly.
-
Impermanent Loss
- A risk faced by liquidity providers when the price of tokens in a liquidity pool changes.
- It occurs because the AMM algorithm rebalances the pool to maintain the x*y=k formula, which can result in LPs holding more of the depreciating asset and less of the appreciating one.
-
Order Book vs. AMM
- Order Book: A traditional system where buyers and sellers place orders, and trades are matched based on price and quantity (e.g., Serum on Solana).
- AMM: A system where trades are executed against liquidity pools using a mathematical formula, eliminating the need for an order book.
-
Slippage
- The difference between the expected price of a trade and the actual price at which the trade is executed.
- Slippage is more common in low-liquidity pools and can be minimized by trading on DEXs with deep liquidity.
-
Yield Farming
- A process where users provide liquidity to DEXs and earn rewards, often in the form of additional tokens.
- Yield farming incentivizes users to contribute to the liquidity of a DEX.
-
Token Swaps
- The process of exchanging one token for another on a DEX.
- Swaps are executed against liquidity pools (in AMMs) or order books (in traditional DEXs).
-
Smart Contracts
- Self-executing programs on the blockchain that automate the execution of trades and other functions on DEXs.
- Solana's smart contracts are known for their speed and low cost, making them ideal for DEXs.
-
Non-Custodial Wallets
- Wallets where users retain full control of their private keys and funds.
- Solana DEXs integrate with non-custodial wallets like Phantom and Solflare.
-
Gas Fees
- The cost of executing transactions on a blockchain.
- Solana's gas fees are extremely low (often less than $0.01), making it cost-effective for trading on DEXs.
-
Cross-Chain Trading
- The ability to trade tokens from different blockchains (e.g., Ethereum, Binance Smart Chain) on a single DEX.
- This is often achieved through bridges or wrapped tokens.
-
Rug Pulls
- A scam where developers abandon a project after attracting liquidity, leaving investors with worthless tokens.
- Rug pulls are a risk in decentralized ecosystems, especially with low-cap tokens.
-
Concentrated Liquidity
- A feature that allows liquidity providers to allocate their funds within specific price ranges, rather than across the entire price spectrum.
- This increases capital efficiency and can lead to higher returns for LPs.
- Example: Orca's Whirlpools.
-
Aggregators
- Platforms that combine liquidity from multiple DEXs to offer users the best possible price for their trades.
- Example: Jupiter on Solana.
-
Front-Running
- A practice where traders or bots exploit advance knowledge of pending transactions to profit at the expense of other users.
- Solana's high speed makes front-running more challenging but not impossible.
-
Memecoins
- Cryptocurrencies inspired by internet memes or jokes, often with little to no utility.
- Many memecoins are traded on Solana DEXs like Raydium and Orca.
-
Rug Checks
- Due diligence performed by traders to assess the legitimacy of a token or project before investing.
- This includes checking the team, tokenomics, and liquidity pool details.
1.2 Key Features of Solana DEXs
Solana is known for its high throughput, low transaction costs, and fast confirmation times, making it an attractive blockchain for building decentralized finance (DeFi) applications, including DEXs.
-
High Speed and Low Fees:
- Solana's blockchain can process up to 65,000 transactions per second (TPS), significantly higher than many other blockchains like Ethereum. This high throughput allows DEXs on Solana to offer near-instant trade execution.
- Transaction fees on Solana are extremely low, often less than $0.01, making it cost-effective for users to trade frequently.
Decentralization: Like all DEXs, Solana DEXs operate without a central authority. Users retain control of their funds through non-custodial wallets (e.g., Phantom, Solflare), and trades are executed via smart contracts.
Automated Market Makers (AMMs): Many Solana DEXs use an AMM model, where liquidity pools replace traditional order books. Users provide liquidity to these pools and earn fees in return, while traders can swap tokens directly from the pools.
Cross-Chain Compatibility: Some Solana DEXs support cross-chain trading, allowing users to trade assets from other blockchains (e.g., Ethereum, Binance Smart Chain) via bridges or wrapped tokens.
User-Friendly Interfaces: Solana DEXs often feature intuitive interfaces, making it easy for both beginners and experienced traders to navigate and execute trades.
1.3 Popular Solana DEXs
Here are some of the most popular Solana-based DEXs:
1.3.1 Raydium
Overview: Raydium is one of the most popular DEXs on Solana. It combines the features of a traditional DEX with access to the Serum order book, enabling faster and more efficient trading.
-
Key Features:
- Automated Market Maker (AMM) and order book integration.
- Liquidity pools for yield farming.
- Supports trading of Solana-based tokens (SPL tokens).
- Staking and governance through the RAY token.
Website: https://raydium.io
1.3.2 Orca
Overview: Orca is a user-friendly DEX on Solana that focuses on simplicity and accessibility. It is known for its clean interface and efficient trading experience.
-
Key Features:
- AMM-based trading with low fees.
- "Whirlpools" for concentrated liquidity.
- Fair pricing and low slippage.
- ORCA token for governance and staking.
Website: https://www.orca.so
1.3.3 Serum
Overview: Serum is a decentralized exchange built on Solana that uses an on-chain order book model. It is known for its high-speed and low-cost trading.
-
Key Features:
- On-chain order book for transparent trading.
- Cross-chain compatibility with other blockchains.
- Integration with other Solana-based DEXs like Raydium.
- SRM token for fee discounts and governance.
Website: https://projectserum.com
1.3.4 Mango Markets
Overview: Mango Markets is a decentralized trading platform on Solana that supports spot trading, margin trading, and lending/borrowing.
-
Key Features:
- Leveraged trading with up to 5x margin.
- Lending and borrowing with competitive interest rates.
- MNGO token for governance.
Website: https://mango.markets
1.3.5 Saber
Overview: Saber is a decentralized exchange optimized for stablecoin and wrapped asset trading. It is designed to facilitate low-slippage swaps.
-
Key Features:
- Focus on stablecoin pairs and pegged assets.
- AMM with low fees and slippage.
- SBR token for governance and rewards.
Website: https://saber.so
1.4 Jupiter Aggregator and Pump.fun
Jupiter Aggregator and Pump.fun are two innovative platforms in the Solana ecosystem, each serving distinct purposes in the decentralized finance (DeFi) and meme coin space.
1.4.1 Jupiter Aggregator
Jupiter Aggregator is a leading liquidity aggregator on the Solana blockchain. It is designed to optimize trading by routing trades across multiple decentralized exchanges (DEXs) to provide users with the best possible prices and lowest slippage.
Key Features:
-
Best Price Execution:
- Jupiter aggregates liquidity from various Solana DEXs (e.g., Raydium, Orca, Serum) to ensure users get the best prices for their trades.
- It splits trades across multiple pools to minimize slippage, especially for large orders.
User-Friendly Interface: The platform offers a simple and intuitive interface, making it easy for both beginners and advanced users to trade efficiently.
Wide Token Support: Jupiter supports a vast array of Solana-based tokens (SPL tokens), including popular and newly launched assets.
-
Advanced Tools:
- Features like limit orders, dollar-cost averaging (DCA), and cross-chain swaps enhance the trading experience.
- Developers can also integrate Jupiter's API into their applications for seamless trading.
Community-Driven: Jupiter has a strong community focus and is governed by its native token, JUP, which is used for governance and staking.
Low Fees: By leveraging Solana's low transaction costs, Jupiter ensures that users pay minimal fees for their trades.
Use Cases:
Retail Traders: Access the best prices and low slippage for trading Solana tokens.
Developers: Integrate Jupiter's liquidity aggregation into DeFi apps.
Institutions: Execute large trades with minimal market impact.
Website: https://jup.ag
1.4.2 Pump.fun
Pump.fun is a unique platform on Solana that allows users to create and trade meme coins easily. It has gained popularity for its simplicity and community-driven approach to launching new tokens.
Key Features:
-
Easy Token Creation:
- Users can create their own meme coins in minutes without any coding knowledge.
- The platform handles the technical aspects, such as deploying the token contract and setting up liquidity pools.
-
Bonding Curve Mechanism:
- Pump.fun uses a bonding curve model to provide liquidity for newly created tokens.
- As more people buy the token, the price increases along the curve, creating a fair and transparent pricing mechanism.
-
Community Engagement:
- Meme coins thrive on community support, and Pump.fun provides tools for creators to promote their tokens and build a following.
- Social features allow users to share and discuss new tokens.
-
Low Barrier to Entry:
- Creating a token on Pump.fun is affordable, making it accessible to a wide range of users.
- The platform takes a small fee from each transaction, which is used to sustain the ecosystem.
Trading and Speculation: Users can trade newly launched meme coins directly on the platform, often leading to high volatility and speculative opportunities.
Integration with Raydium: Once a token reaches a certain market cap, it is automatically listed on Raydium, a major Solana DEX, providing additional liquidity and exposure.
Use Cases:
Meme Coin Creators: Launch and promote their own tokens with minimal effort.
Traders: Speculate on newly created meme coins for potential profits.
Communities: Build and support tokens around shared interests or memes.
Website: https://pump.fun
1.5 Sniper bot vs. Solana DEXs
Sniper bots and Solana DEXs have a unique relationship in the decentralized finance (DeFi) ecosystem. Sniper bots are automated tools designed to execute trades quickly and efficiently, often targeting newly launched tokens as soon as they become available on a DEX.
How Sniper Bots Work on Solana DEXs
Solana's high throughput (up to 65,000 transactions per second) and low transaction fees make it an ideal environment for sniper bots.
-
Monitoring New Token Launches:
- Sniper bots scan Solana DEXs (e.g., Raydium, Orca, Serum) for newly listed tokens.
- They analyze liquidity pool creation and token launch events to identify opportunities.
-
Fast Execution:
- Once a new token is detected, the bot quickly executes a buy order to acquire the token at the lowest possible price.
- Solana's fast block times (400ms) allow bots to act almost instantaneously.
-
Liquidity Pool Analysis:
- Bots monitor liquidity pools to identify tokens with low liquidity, which are more susceptible to price manipulation.
- They can exploit these conditions to buy tokens cheaply and sell them at a higher price.
-
Arbitrage:
- Sniper bots (Arbitrage bots) identify price differences for the same token across multiple Solana DEXs.
- They buy the token on the cheaper DEX and sell it on the more expensive one, profiting from the price discrepancy.
-
Automated Selling:
- Bots can be programmed to sell tokens when they reach a specific price target or when market conditions change.
- This allows traders to lock in profits or minimize losses.
Relationship Between Sniper Bots and Solana DEXs
-
Enhanced Liquidity:
- Sniper bots contribute to liquidity on Solana DEXs by actively trading and participating in liquidity pools.
- However, their activity can sometimes lead to short-term price volatility.
Market Efficiency: By exploiting arbitrage opportunities, sniper bots help align prices across different DEXs, making markets more efficient.
-
Competitive Edge:
- Sniper bots give their users a significant advantage in trading, especially for newly launched tokens or low-liquidity assets.
- This can create an uneven playing field for retail traders who do not use such tools.
-
Token Launches:
- On platforms like Pump.fun, sniper bots are often used to buy newly created meme coins as soon as they are launched.
- This can lead to rapid price increases, followed by sell-offs as bots take profits.
-
Risks and Challenges:
- Sniper bots can contribute to market manipulation, such as pump-and-dump schemes.
- They may also increase competition for retail traders, making it harder to buy tokens at favorable prices.
2. How to swap Token A and Token B
Token Swap on Solana DEX
A token swap on a Solana DEX involves exchanging one type of token for another. For example, you might swap SOL (Solana's native token) for USDC (a stablecoin) or any other SPL token (Solana Program Library token). This process is facilitated by smart contracts and liquidity pools on the DEX.
Token Buy/Sell as a Token Swap
When you "buy" or "sell" a token on a Solana DEX, you're essentially performing a token swap:
Buying a Token: If you want to "buy" a token, you're swapping a base token (like SOL or USDC) for the desired token.
Selling a Token: If you want to "sell" a token, you're swapping the token you hold for another token (like SOL or USDC).
Example
Let's say you want to buy RAY (Raydium's token) on a Solana DEX:
You start with SOL in your wallet.
You initiate a swap on the DEX, exchanging SOL for RAY.
The DEX's smart contract routes your transaction through a liquidity pool (e.g., SOL/RAY pool) and gives you RAY in exchange for SOL.
In this case, "buying" RAY is the same as performing a token swap from SOL to RAY.
Key Points
Liquidity Pools: Token swaps rely on liquidity pools, where users provide tokens to enable trading. The price of the swap is determined by the ratio of tokens in the pool.
Slippage: The price you get for your swap may vary slightly due to market activity and pool size.
Fees: Most DEXs charge a small fee for swaps, which is distributed to liquidity providers.
Let's develop a script to buy/sell SPL tokens (In this case, token A is SOL, and token B is a SPL token that you are gonna buy or sell).
Step 1: Setup Environment
- For convenience, let's develop our own code using VS Code. Let's assume that you have installed Node.js (version 18.0 or later).
- Also, we need a wallet with some SOL. To buy/sell SPL token, you will need the private key of wallet.
- Initialize your project using
npm init
. - Install dependencies using this command:
npm install typescript ts-node @project-serum/anchor @solana/web3.js @solana/spl-token axios dotenv bs58
- Check
package.json
file and edit scripts like this:
{
"name": "token-swap",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "ts-node index.ts",
"build": "tsc",
"clean": "tsc --build --clean",
"dev": "tsc && ts-node ./dist/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@project-serum/anchor": "^0.26.0",
"@solana/spl-token": "^0.4.12",
"@solana/web3.js": "^1.98.0",
"axios": "^1.7.9",
"bs58": "^6.0.0",
"dotenv": "^16.4.7",
"ts-node": "^10.9.2",
"typescript": "^5.7.3"
}
}
- Install Typescript environment using
tsc --init
command. - Edit
tsconfig.json
file like this:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
- .env file
WALLET_PRIVATE_KEY=""
RPC_URL=""
Step 2: Main code (2 files)
-
index.ts
file This code buy/sell SPL token with SOL in your wallet.
import {
Connection,
Keypair,
PublicKey,
LAMPORTS_PER_SOL,
VersionedTransaction,
} from "@solana/web3.js";
import { NATIVE_MINT } from "@solana/spl-token";
import bs58 from "bs58";
import dotenv from "dotenv";
import { Wallet } from "@project-serum/anchor";
import { getSwapInfo, getSwapTransaction } from "./jupiterService";
dotenv.config();
const WALLET_PRIVATE_KEY = process.env.WALLET_PRIVATE_KEY as string;
const RPC_URL = process.env.RPC_URL as string;
const wallet = Keypair.fromSecretKey(bs58.decode(WALLET_PRIVATE_KEY));
const anchorWallet = new Wallet(wallet);
async function SplTokenSwap(
tokenAddress: string,
amount: number,
isBuySell: string
) {
const connection = new Connection(RPC_URL, "confirmed");
const tokenDecimals = await getTokenDecimals(connection, tokenAddress);
const slippageBps = parseInt(process.env.SLIPPAGEBPS || "") || 50;
let swapInfo: any;
if (isBuySell == "buy") {
swapInfo = await getSwapInfo(
NATIVE_MINT.toBase58(),
tokenAddress,
amount * LAMPORTS_PER_SOL,
slippageBps
);
} else {
// sell
swapInfo = await getSwapInfo(
tokenAddress,
NATIVE_MINT.toBase58(),
amount * Math.pow(10, tokenDecimals),
slippageBps
);
}
const swapTransaction = await getSwapTransaction(swapInfo, anchorWallet);
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
const latestBlockHash = await connection.getLatestBlockhash();
const versionedTransaction =
VersionedTransaction.deserialize(swapTransactionBuf);
versionedTransaction.message.recentBlockhash = latestBlockHash.blockhash;
versionedTransaction.sign([anchorWallet.payer]);
try {
const transactionSignature = await connection.sendTransaction(
versionedTransaction,
{ maxRetries: 20 }
);
const confirmation = await connection.confirmTransaction(
{
signature: transactionSignature,
blockhash: latestBlockHash.blockhash,
lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
},
"confirmed"
);
if (confirmation.value.err) {
throw new Error("Transaction not confirmed");
}
console.log(
"Transaction Signature: ",
`https://solscan.io/tx/${transactionSignature}`
);
} catch (error) {
console.error("Error occurred during swap:", error);
}
}
async function getTokenDecimals(connection: Connection, tokenAddress: string) {
const mintInfo = await connection.getParsedAccountInfo(
new PublicKey(tokenAddress)
);
if (!mintInfo) {
throw new Error("Token account not found");
}
const decimals = (mintInfo.value?.data as any).parsed.info.decimals;
return decimals;
}
const TOKEN_ADDRESS = "4aR3jtFKWuYzkNE27WG4V7Jt6DDhwKcc2qjzN5Tkpump";
let amount: number;
amount = 0.0001;
SplTokenSwap(TOKEN_ADDRESS, amount, "buy"); // Buy token
amount = 1000;
SplTokenSwap(TOKEN_ADDRESS, amount, "sell"); // Sell token
-
jupiterService.ts
file
import { Wallet } from "@project-serum/anchor";
import axios from "axios";
const JUP_API = "https://api.jup.ag/swap/v1";
export const getSwapInfo = async (tokenA: string, tokenB: string, amount: number, slippageBps: number) => {
const res = await axios.get(`${JUP_API}/quote?inputMint=${tokenA}&outputMint=${tokenB}&amount=${amount}&slippageBps=${slippageBps}`);
const swapinfo = res.data;
return swapinfo;
};
export const getSwapTransaction = async (quoteResponse: any, anchorWallet: Wallet) => {
const swapResponse = await axios.post(`${JUP_API}/swap`, {
quoteResponse,
userPublicKey: anchorWallet.publicKey.toString(),
wrapAndUnwrapSol: true,
prioritizationFeeLamports: 200000, // or custom lamports: 1000
});
return swapResponse.data.swapTransaction
};
Step 3: Run the code
- In terminal, run this command:
npm run start
- If the transaction is successful, you will receive a transaction link from solscan.
3. What will be in the next issue?
In the next issue, I will explain about Telegram Bot development.
Top comments (0)