docs: remove token creation sections
This commit is contained in:
@@ -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
|
||||
|
||||
+11
-56
@@ -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服务客户端
|
||||
|
||||
-161
@@ -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<String>,
|
||||
/// Telegram handle
|
||||
pub telegram: Option<String>,
|
||||
/// Website URL
|
||||
pub website: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
/// Optional Telegram group
|
||||
pub telegram: Option<String>,
|
||||
/// Optional website URL
|
||||
pub website: Option<String>,
|
||||
|
||||
pub metadata_uri: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn create_token_metadata(metadata: CreateTokenMetadata, api_token: &str) -> Result<TokenMetadataIPFS, anyhow::Error> {
|
||||
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<String, anyhow::Error> {
|
||||
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<String, anyhow::Error> {
|
||||
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)
|
||||
}
|
||||
-59
@@ -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;
|
||||
@@ -24,7 +23,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};
|
||||
@@ -145,63 +143,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<u64>,
|
||||
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<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
buy_sol_cost: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
recent_blockhash: Hash,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
pumpfun::create::create_and_buy_with_tip(
|
||||
self.rpc.clone(),
|
||||
self.fee_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(
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
use std::{str::FromStr, time::Instant, sync::Arc};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use solana_hash::Hash;
|
||||
use solana_sdk::{
|
||||
compute_budget::ComputeBudgetInstruction,
|
||||
instruction::Instruction, message::{v0, VersionedMessage},
|
||||
pubkey::Pubkey,
|
||||
native_token::sol_to_lamports,
|
||||
signature::Keypair,
|
||||
signer::Signer,
|
||||
system_instruction,
|
||||
transaction::{Transaction, VersionedTransaction}
|
||||
};
|
||||
use spl_associated_token_account::instruction::create_associated_token_account;
|
||||
|
||||
use crate::{
|
||||
common::{PriorityFee, SolanaRpcClient}, constants, instruction,
|
||||
ipfs::TokenMetadataIPFS, swqos::{FeeClient, TradeType},
|
||||
};
|
||||
|
||||
use crate::pumpfun::common::{
|
||||
create_priority_fee_instructions,
|
||||
get_buy_amount_with_slippage, get_global_account
|
||||
};
|
||||
|
||||
use crate::common::tip_cache::TipCache;
|
||||
|
||||
use super::common::{get_bonding_curve_account, get_buy_token_amount, get_creator_vault_pda};
|
||||
|
||||
/// Create a new token
|
||||
pub async fn create(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let mut instructions = create_priority_fee_instructions(priority_fee);
|
||||
|
||||
instructions.push(instruction::create(
|
||||
payer.as_ref(),
|
||||
&mint,
|
||||
instruction::Create {
|
||||
_name: ipfs.metadata.name,
|
||||
_symbol: ipfs.metadata.symbol,
|
||||
_uri: ipfs.metadata_uri,
|
||||
_creator: payer.pubkey(),
|
||||
},
|
||||
));
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&instructions,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref(), &mint],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create and buy tokens in one transaction
|
||||
pub async fn create_and_buy(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
buy_sol_cost: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
recent_blockhash: Hash,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
if buy_sol_cost == 0 {
|
||||
return Err(anyhow!("Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let mint = Arc::new(mint);
|
||||
let transaction = build_create_and_buy_transaction(rpc.clone(), payer.clone(), mint.clone(), ipfs, buy_sol_cost, slippage_basis_points, priority_fee.clone(), recent_blockhash).await?;
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create_and_buy_with_tip(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
fee_clients: Vec<Arc<FeeClient>>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
buy_sol_cost: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
recent_blockhash: Hash,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let start_time = Instant::now();
|
||||
let mint = Arc::new(mint);
|
||||
let build_instructions = build_create_and_buy_instructions(rpc.clone(), payer.clone(), mint.clone(), ipfs.clone(), buy_sol_cost, slippage_basis_points).await?;
|
||||
let mut handles = vec![];
|
||||
for fee_client in fee_clients {
|
||||
let tip_account = fee_client.get_tip_account()?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
|
||||
let transaction = build_create_and_buy_transaction_with_tip(/*rpc.clone(),*/ tip_account, payer.clone(), priority_fee.clone(), build_instructions.clone(), recent_blockhash).await?;
|
||||
let handle = tokio::spawn(async move {
|
||||
fee_client.send_transaction(TradeType::CreateAndBuy, &transaction).await.map_err(|e| anyhow!(e.to_string()))?;
|
||||
println!("Total Jito create and buy operation time: {:?}ms", start_time.elapsed().as_millis());
|
||||
Ok::<(), anyhow::Error>(())
|
||||
});
|
||||
|
||||
handles.push(handle);
|
||||
}
|
||||
|
||||
for handle in handles {
|
||||
match handle.await {
|
||||
Ok(Ok(_)) => (),
|
||||
Ok(Err(e)) => println!("Error in task: {}", e),
|
||||
Err(e) => println!("Task join error: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn build_create_and_buy_transaction(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Arc<Keypair>,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
buy_sol_cost: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
recent_blockhash: Hash,
|
||||
) -> Result<Transaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
];
|
||||
|
||||
let build_instructions = build_create_and_buy_instructions(rpc.clone(), payer.clone(), mint.clone(), ipfs, buy_sol_cost, slippage_basis_points).await?;
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
// let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
// let recent_blockhash = Hash::default();
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&instructions,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref(), mint.as_ref()],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_create_and_buy_transaction_with_tip(
|
||||
// rpc: Arc<SolanaRpcClient>,
|
||||
tip_account: Arc<Pubkey>,
|
||||
payer: Arc<Keypair>,
|
||||
priority_fee: PriorityFee,
|
||||
build_instructions: Vec<Instruction>,
|
||||
recent_blockhash: Hash,
|
||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||
let tip_cache = TipCache::get_instance();
|
||||
let tip_amount = tip_cache.get_tip();
|
||||
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
system_instruction::transfer(
|
||||
&payer.pubkey(),
|
||||
&tip_account,
|
||||
sol_to_lamports(tip_amount),
|
||||
),
|
||||
];
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
// let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
// let recent_blockhash = Hash::default();
|
||||
let v0_message: v0::Message =
|
||||
v0::Message::try_compile(&payer.pubkey(), &instructions, &[], recent_blockhash)?;
|
||||
|
||||
let versioned_message: VersionedMessage = VersionedMessage::V0(v0_message);
|
||||
let transaction = VersionedTransaction::try_new(versioned_message, &[&payer])?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_create_and_buy_instructions(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Arc<Keypair>,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
buy_sol_cost: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||
if buy_sol_cost == 0 {
|
||||
return Err(anyhow!("Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let (bonding_curve_account, bonding_curve_pda) = get_bonding_curve_account(&rpc, &mint.pubkey()).await?;
|
||||
let creator_vault_pda = get_creator_vault_pda(&bonding_curve_account.creator).unwrap();
|
||||
let (buy_token_amount, max_sol_cost) = get_buy_token_amount(&bonding_curve_account, buy_sol_cost, slippage_basis_points)?;
|
||||
|
||||
let mut instructions = vec![];
|
||||
|
||||
instructions.push(instruction::create(
|
||||
payer.as_ref(),
|
||||
mint.as_ref(),
|
||||
instruction::Create {
|
||||
_name: ipfs.metadata.name.clone(),
|
||||
_symbol: ipfs.metadata.symbol.clone(),
|
||||
_uri: ipfs.metadata_uri.clone(),
|
||||
_creator: payer.pubkey(),
|
||||
},
|
||||
));
|
||||
|
||||
instructions.push(create_associated_token_account(
|
||||
&payer.pubkey(),
|
||||
&payer.pubkey(),
|
||||
&mint.pubkey(),
|
||||
&constants::pumpfun::accounts::TOKEN_PROGRAM,
|
||||
));
|
||||
|
||||
instructions.push(instruction::buy(
|
||||
payer.as_ref(),
|
||||
&mint.pubkey(),
|
||||
&bonding_curve_pda,
|
||||
&creator_vault_pda,
|
||||
&constants::pumpfun::global_constants::FEE_RECIPIENT,
|
||||
instruction::Buy {
|
||||
_amount: buy_token_amount,
|
||||
_max_sol_cost: max_sol_cost,
|
||||
},
|
||||
));
|
||||
|
||||
Ok(instructions)
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod buy;
|
||||
pub mod create;
|
||||
pub mod sell;
|
||||
pub mod common;
|
||||
Reference in New Issue
Block a user