diff --git a/README.md b/README.md index 23871ec..1264668 100755 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A comprehensive Rust SDK for seamless interaction with Solana DEX trading progra ## Features -1. **PumpFun Trading**: Support for `create`, `buy`, `sell` operations +1. **PumpFun Trading**: Support for `buy`, `sell` operations 2. **PumpSwap Trading**: Support for PumpSwap pool trading operations 3. **Raydium Trading**: Support for Raydium DEX trading operations 4. **Logs Subscription**: Subscribe to PumpFun, PumpSwap, and Raydium program transaction logs @@ -12,8 +12,7 @@ A comprehensive Rust SDK for seamless interaction with Solana DEX trading progra 6. **ShredStream Support**: Subscribe to program logs using ShredStream 7. **Multiple MEV Protection**: Support for Jito, Nextblock, 0slot, Nozomi services 8. **Concurrent Transactions**: Submit transactions using multiple MEV services simultaneously; the fastest succeeds while others fail -9. **IPFS Integration**: Support for token metadata IPFS uploads -10. **Real-time Pricing**: Get real-time token prices and liquidity information +9. **Real-time Pricing**: Get real-time token prices and liquidity information ## Installation @@ -33,7 +32,7 @@ sol-trade-sdk = { path = "./sol-trade-sdk", version = "0.1.0" } ## Usage Examples -### 1. Logs Subscription - Monitor Token Creation and Trading +### 1. Logs Subscription - Monitor Token Trading ```rust use sol_trade_sdk::{common::pumpfun::logs_events::PumpfunEvent, grpc::YellowstoneGrpc}; @@ -109,52 +108,9 @@ let payer = Keypair::from_base58_string("your_private_key"); let solana_trade_client = SolanaTrade::new(Arc::new(payer), &cluster).await; ``` -### 3. Create Token +### 3. Buy Tokens -```rust -use sol_trade_sdk::{ipfs::CreateTokenMetadata, ipfs::create_token_metadata}; -use solana_sdk::signature::Keypair; - -// Create token keypair -let mint_keypair = Keypair::new(); - -// Prepare token metadata -let metadata = CreateTokenMetadata { - name: "My Token".to_string(), - symbol: "MTK".to_string(), - description: "This is a test token".to_string(), - file: "path/to/image.png".to_string(), // Local file path - twitter: Some("https://twitter.com/example".to_string()), - telegram: Some("https://t.me/example".to_string()), - website: Some("https://example.com".to_string()), - metadata_uri: None, // Will be generated -}; - -// Upload metadata to IPFS -let api_token = "your_pinata_api_token"; -let ipfs_response = create_token_metadata(metadata, api_token).await?; - -// Create token -solana_trade_client.create(mint_keypair, ipfs_response).await?; -``` - -### 3.1. Create and Buy Token (with MEV protection) - -```rust -// Create token and buy simultaneously with MEV protection -solana_trade_client.create_and_buy_with_tip( - payer.clone(), // payer keypair - mint_keypair, // mint keypair - ipfs_response, // IPFS response - 50000000, // buy_sol_cost (purchase amount in lamports, 0.05 SOL) - Some(100), // slippage (1%) - recent_blockhash, -).await?; -``` - -### 4. Buy Tokens - -### 4.1 Buy Tokens --- Sniping +### 3.1 Buy Tokens --- Sniping ```rust use solana_sdk::{pubkey::Pubkey, hash::Hash}; use std::sync::Arc; @@ -192,7 +148,7 @@ solana_trade_client.sniper_buy_with_tip( ).await?; ``` -### 4.2 Buy Tokens --- Copy Trading +### 3.2 Buy Tokens --- Copy Trading ```rust use solana_sdk::{pubkey::Pubkey, hash::Hash}; use std::sync::Arc; @@ -244,7 +200,7 @@ solana_trade_client.buy_with_tip( ).await?; ``` -### 5. Sell Tokens +### 4. Sell Tokens ```rust // Sell by amount @@ -267,7 +223,7 @@ solana_trade_client.sell_by_percent_with_tip( ).await?; ``` -### 6. Get Price and Balance Information +### 5. Get Price and Balance Information ```rust // Get current token price @@ -287,7 +243,7 @@ let sol_reserves = solana_trade_client.get_real_sol_reserves(&mint_pubkey).await println!("SOL reserves: {} lamports", sol_reserves); ``` -### 7. PumpSwap Subscription - Monitor AMM Events +### 6. PumpSwap Subscription - Monitor AMM Events ```rust use sol_trade_sdk::{common::pumpswap::logs_events::PumpSwapEvent, grpc::YellowstoneGrpc}; @@ -333,7 +289,7 @@ println!("Monitoring PumpSwap events, press Ctrl+C to stop..."); client.subscribe_pumpswap(callback).await?; ``` -### 8. PumpSwap Trading Operations +### 7. PumpSwap Trading Operations ```rust use std::sync::Arc; @@ -397,7 +353,7 @@ solana_trade_client .await?; ``` -### 9. PumpSwap Pool Information +### 8. PumpSwap Pool Information ```rust use solana_sdk::pubkey::Pubkey; @@ -440,7 +396,6 @@ src/ ├── error/ # Error handling ├── grpc/ # gRPC clients ├── instruction/ # Instruction building -├── ipfs/ # IPFS integration ├── pumpfun/ # PumpFun trading functionality ├── pumpswap/ # PumpSwap trading functionality ├── swqos/ # MEV service clients diff --git a/README_CN.md b/README_CN.md index 70616fa..a6ff479 100755 --- a/README_CN.md +++ b/README_CN.md @@ -4,7 +4,7 @@ ## 项目特性 -1. **PumpFun交易**: 支持`创建代币`、`购买`、`卖出`功能 +1. **PumpFun交易**: 支持`购买`、`卖出`功能 2. **PumpSwap交易**: 支持PumpSwap池的交易操作 3. **Raydium交易**: 支持Raydium DEX的交易操作 4. **日志订阅**: 订阅PumpFun、PumpSwap和Raydium程序的交易日志 @@ -12,8 +12,7 @@ 6. **ShredStream支持**: 使用ShredStream订阅程序日志 7. **多种MEV保护**: 支持Jito、Nextblock、0slot、Nozomi等服务 8. **并发交易**: 同时使用多个MEV服务发送交易,最快的成功,其他失败 -9. **IPFS集成**: 支持代币元数据的IPFS上传 -10. **实时价格**: 获取代币实时价格和流动性信息 +9. **实时价格**: 获取代币实时价格和流动性信息 ## 安装 @@ -33,7 +32,7 @@ sol-trade-sdk = { path = "./sol-trade-sdk", version = "0.1.0" } ## 使用示例 -### 1. 日志订阅 - 监听代币创建和交易 +### 1. 日志订阅 - 监听代币交易 ```rust use sol_trade_sdk::{common::pumpfun::logs_events::PumpfunEvent, grpc::YellowstoneGrpc}; @@ -109,52 +108,9 @@ let payer = Keypair::from_base58_string("your_private_key"); let solana_trade_client = SolanaTrade::new(Arc::new(payer), &cluster).await; ``` -### 3. 创建代币 +### 3. 购买代币 -```rust -use sol_trade_sdk::{ipfs::CreateTokenMetadata, ipfs::create_token_metadata}; -use solana_sdk::signature::Keypair; - -// 创建代币密钥对 -let mint_keypair = Keypair::new(); - -// 准备代币元数据 -let metadata = CreateTokenMetadata { - name: "我的代币".to_string(), - symbol: "MTK".to_string(), - description: "这是一个测试代币".to_string(), - file: "path/to/image.png".to_string(), // 本地文件路径 - twitter: Some("https://twitter.com/example".to_string()), - telegram: Some("https://t.me/example".to_string()), - website: Some("https://example.com".to_string()), - metadata_uri: None, // 将自动生成 -}; - -// 上传元数据到IPFS -let api_token = "your_pinata_api_token"; -let ipfs_response = create_token_metadata(metadata, api_token).await?; - -// 创建代币 -solana_trade_client.create(mint_keypair, ipfs_response).await?; -``` - -### 3.1. 创建并购买代币(带小费) - -```rust -// 创建代币的同时购买,并使用MEV保护 -solana_trade_client.create_and_buy_with_tip( - payer.clone(), // payer keypair - mint_keypair, // mint keypair - ipfs_response, // IPFS响应 - 50000000, // buy_sol_cost (购买金额,lamports,0.05 SOL) - Some(100), // slippage (1%) - recent_blockhash, -).await?; -``` - -### 4. 购买代币 - -### 4.1 购买代币 --- 狙击 +### 3.1 购买代币 --- 狙击 ```rust use solana_sdk::{pubkey::Pubkey, hash::Hash}; use std::sync::Arc; @@ -192,7 +148,7 @@ solana_trade_client.sniper_buy_with_tip( ).await?; ``` -### 4.2 购买代币 --- 跟单 +### 3.2 购买代币 --- 跟单 ```rust use solana_sdk::{pubkey::Pubkey, hash::Hash}; use std::sync::Arc; @@ -244,7 +200,7 @@ solana_trade_client.buy_with_tip( ).await?; ``` -### 5. 卖出代币 +### 4. 卖出代币 ```rust // 按数量卖出 @@ -267,7 +223,7 @@ solana_trade_client.sell_by_percent_with_tip( ).await?; ``` -### 6. 获取价格和余额信息 +### 5. 获取价格和余额信息 ```rust // 获取代币当前价格 @@ -287,7 +243,7 @@ let sol_reserves = solana_trade_client.get_real_sol_reserves(&mint_pubkey).await println!("SOL储备: {} lamports", sol_reserves); ``` -### 7. PumpSwap订阅 - 监听AMM事件 +### 6. PumpSwap订阅 - 监听AMM事件 ```rust use sol_trade_sdk::{common::pumpswap::logs_events::PumpSwapEvent, grpc::YellowstoneGrpc}; @@ -333,7 +289,7 @@ println!("开始监听PumpSwap事件,按Ctrl+C停止..."); client.subscribe_pumpswap(callback).await?; ``` -### 8. PumpSwap交易操作 +### 7. PumpSwap交易操作 ```rust use std::sync::Arc; @@ -397,7 +353,7 @@ solana_trade_client .await?; ``` -### 9. PumpSwap池信息 +### 8. PumpSwap池信息 ```rust use solana_sdk::pubkey::Pubkey; @@ -440,7 +396,6 @@ src/ ├── error/ # 错误处理 ├── grpc/ # gRPC客户端 ├── instruction/ # 指令构建 -├── ipfs/ # IPFS集成 ├── pumpfun/ # PumpFun交易功能 ├── pumpswap/ # PumpSwap交易功能 ├── swqos/ # MEV服务客户端 diff --git a/src/ipfs/mod.rs b/src/ipfs/mod.rs deleted file mode 100755 index fc0afb5..0000000 --- a/src/ipfs/mod.rs +++ /dev/null @@ -1,161 +0,0 @@ -use std::time::Duration; - -use serde_json::Value; -use tokio::fs::File; -use tokio::io::AsyncReadExt; -use reqwest::Client; -use reqwest::multipart::{Form, Part}; -use base64::{Engine as _, engine::general_purpose}; -use serde::{Deserialize, Serialize}; - -/// Metadata structure for a token, matching the format expected by Pump.fun. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TokenMetadata { - /// Name of the token - pub name: String, - /// Token symbol (e.g. "BTC") - pub symbol: String, - /// Description of the token - pub description: String, - /// IPFS URL of the token's image - pub image: String, - /// Whether to display the token's name - pub show_name: bool, - /// Creation timestamp/source - pub created_on: String, - /// Twitter handle - pub twitter: Option, - /// Telegram handle - pub telegram: Option, - /// Website URL - pub website: Option, -} - -/// Response received after successfully uploading token metadata. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TokenMetadataIPFS { - /// The uploaded token metadata - pub metadata: TokenMetadata, - /// IPFS URI where the metadata is stored - pub metadata_uri: String, -} - -/// Parameters for creating new token metadata. -#[derive(Debug, Clone)] -pub struct CreateTokenMetadata { - /// Name of the token - pub name: String, - /// Token symbol (e.g. "BTC") - pub symbol: String, - /// Description of the token - pub description: String, - /// Path to the token's image file - pub file: String, - /// Optional Twitter handle - pub twitter: Option, - /// Optional Telegram group - pub telegram: Option, - /// Optional website URL - pub website: Option, - - pub metadata_uri: Option, -} - -pub async fn create_token_metadata(metadata: CreateTokenMetadata, api_token: &str) -> Result { - let ipfs_url = if metadata.file.starts_with("http") || metadata.metadata_uri.is_some() { - metadata.file - } else { - let base64_string = file_to_base64(&metadata.file).await?; - upload_base64_file(&base64_string, api_token).await? - }; - - let token_metadata = TokenMetadata { - name: metadata.name, - symbol: metadata.symbol, - description: metadata.description, - image: ipfs_url, - show_name: true, - created_on: "https://pump.fun".to_string(), - twitter: metadata.twitter, - telegram: metadata.telegram, - website: metadata.website, - }; - - if metadata.metadata_uri.is_some() { - let token_metadata_ipfs = TokenMetadataIPFS { - metadata: token_metadata, - metadata_uri: metadata.metadata_uri.unwrap(), - }; - Ok(token_metadata_ipfs) - } else { - let client = Client::new(); - let response = client - .post("https://api.pinata.cloud/pinning/pinJSONToIPFS") - .header("Content-Type", "application/json") - .header("Authorization", format!("Bearer {}", api_token)) - .json(&token_metadata) - .send() - .await?; - - // 确保请求成功 - if response.status().is_success() { - let res_data: serde_json::Value = response.json().await?; - let ipfs_hash = res_data["IpfsHash"].as_str().unwrap(); - let ipfs_url = format!("https://ipfs.io/ipfs/{}", ipfs_hash); - let token_metadata_ipfs = TokenMetadataIPFS { - metadata: token_metadata, - metadata_uri: ipfs_url, - }; - Ok(token_metadata_ipfs) - } else { - eprintln!("Error: {:?}", response.text().await?); - Err(anyhow::anyhow!("Failed to create token metadata")) - } - } -} - -pub async fn upload_base64_file(base64_string: &str, api_token: &str) -> Result { - let decoded_bytes = general_purpose::STANDARD.decode(base64_string)?; - - let client = Client::builder() - .timeout(Duration::from_secs(120)) // 增加超时时间到120秒 - .pool_max_idle_per_host(0) // 禁用连接池 - .pool_idle_timeout(None) // 禁用空闲超时 - .build()?; - - let part = Part::bytes(decoded_bytes) - .file_name("file.png") // 添加文件扩展名 - .mime_str("image/png")?; // 指定正确的MIME类型 - - let form = Form::new().part("file", part); - - let response = client - .post("https://api.pinata.cloud/pinning/pinFileToIPFS") - .header("Authorization", format!("Bearer {}", api_token)) - .header("Accept", "application/json") - .multipart(form) - .send() - .await?; - - if response.status().is_success() { - let response_json: Value = response.json().await.map_err(|e| anyhow::anyhow!("Failed to parse JSON: {}", e))?; - println!("{:#?}", response_json); - let ipfs_hash = response_json["IpfsHash"].as_str().unwrap(); - let ipfs_url = format!("https://ipfs.io/ipfs/{}", ipfs_hash); - Ok(ipfs_url) - } else { - let error_text = response.text().await?; - eprintln!("Error: {:?}", error_text); - Err(anyhow::anyhow!("Failed to upload file to IPFS: {}", error_text)) - } -} - -async fn file_to_base64(file_path: &str) -> Result { - let mut file = File::open(file_path).await?; - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer).await?; - let base64_string = general_purpose::STANDARD.encode(&buffer); - Ok(base64_string) -} diff --git a/src/lib.rs b/src/lib.rs index 95cde5e..e11202d 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,6 @@ pub mod error; pub mod instruction; pub mod grpc; pub mod common; -pub mod ipfs; pub mod swqos; pub mod pumpfun; pub mod pumpswap; @@ -25,7 +24,6 @@ use solana_sdk::{ use common::{pumpfun::logs_data::TradeInfo, pumpfun::logs_events::PumpfunEvent, pumpfun::logs_subscribe, Cluster, PriorityFee, SolanaRpcClient}; use common::pumpfun::logs_subscribe::SubscriptionHandle; -use ipfs::TokenMetadataIPFS; use constants::trade_type::{COPY_BUY, SNIPER_BUY}; use constants::trade_platform::{PUMPFUN, PUMPFUN_SWAP, RAYDIUM}; @@ -151,63 +149,6 @@ impl SolanaTrade { let instance = INSTANCE.lock().unwrap(); instance.as_ref().expect("PumpFun instance not initialized. Please call new() first.").clone() } - - /// Create a new token - pub async fn create( - &self, - mint: Keypair, - ipfs: TokenMetadataIPFS, - ) -> Result<(), anyhow::Error> { - pumpfun::create::create( - self.rpc.clone(), - self.payer.clone(), - mint, - ipfs, - self.priority_fee.clone(), - ).await - } - - pub async fn create_and_buy( - &self, - mint: Keypair, - ipfs: TokenMetadataIPFS, - amount_sol: u64, - slippage_basis_points: Option, - recent_blockhash: Hash, - ) -> Result<(), anyhow::Error> { - pumpfun::create::create_and_buy( - self.rpc.clone(), - self.payer.clone(), - mint, - ipfs, - amount_sol, - slippage_basis_points, - self.priority_fee.clone(), - recent_blockhash, - ).await - } - - pub async fn create_and_buy_with_tip( - &self, - payer: Arc, - mint: Keypair, - ipfs: TokenMetadataIPFS, - buy_sol_cost: u64, - slippage_basis_points: Option, - recent_blockhash: Hash, - ) -> Result<(), anyhow::Error> { - pumpfun::create::create_and_buy_with_tip( - self.rpc.clone(), - self.swqos_clients.clone(), - payer, - mint, - ipfs, - buy_sol_cost, - slippage_basis_points, - self.priority_fee.clone(), - recent_blockhash, - ).await - } /// Buy tokens pub async fn sniper_buy( diff --git a/src/pumpfun/mod.rs b/src/pumpfun/mod.rs index 8126389..663177e 100755 --- a/src/pumpfun/mod.rs +++ b/src/pumpfun/mod.rs @@ -1,4 +1,3 @@ pub mod buy; -pub mod create; pub mod sell; pub mod common; \ No newline at end of file