-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
363 lines (298 loc) · 11.1 KB
/
main.py
File metadata and controls
363 lines (298 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
"""
Solana Volume Bot 主程式
使用 Jupiter Exchange API 執行自動交易循環
"""
import asyncio
import sys
from typing import Optional
from solana.rpc.async_api import AsyncClient
from config import (
BotConfig,
ConfigError,
load_config,
print_config_summary,
validate_config,
)
from jupiter_client import JupiterClient
from logger import init_logger, get_logger
from scheduler import BotScheduler, get_user_choice, ask_run_immediately
from wallet_manager import Wallet, WalletManager, WalletError
class VolumeBot:
"""Volume Bot 主類"""
def __init__(self, config: BotConfig):
"""
初始化 Volume Bot
Args:
config: Bot 配置
"""
self.config = config
self.logger = get_logger()
# 初始化 RPC 客戶端
self.rpc_client = AsyncClient(config.rpc_endpoint)
# 初始化錢包管理器
self.wallet_manager = WalletManager(config.wallet_private_keys)
# 初始化 Jupiter 客戶端
self.jupiter_client = JupiterClient(
api_url=config.jupiter_api_url,
rpc_client=self.rpc_client,
api_key=config.jupiter_api_key,
slippage_bps=config.slippage_bps,
max_retries=config.max_retries,
retry_delay=config.retry_delay,
)
# 統計數據
self.total_success = 0
self.total_failed = 0
async def check_wallet_balance(self, wallet: Wallet) -> bool:
"""
檢查錢包餘額
Args:
wallet: 錢包實例
Returns:
餘額足夠返回 True,否則返回 False
"""
sol_balance = await wallet.get_sol_balance(self.rpc_client)
usdc_balance = await wallet.get_usdc_balance(
self.rpc_client, self.config.usdc_mint
)
self.logger.log_balance(wallet.address, sol_balance, usdc_balance)
# 檢查 SOL 餘額是否足夠(需要 swap_amount + 交易費用)
min_required_sol = self.config.swap_amount_sol + 0.01 # 預留 0.01 SOL 作為手續費
if sol_balance < min_required_sol:
self.logger.warning(
f"⚠️ SOL 餘額不足!當前: {sol_balance:.6f} SOL,"
f"需要: {min_required_sol:.6f} SOL"
)
return False
return True
async def execute_cycle(
self, wallet: Wallet, cycle_num: int, total_cycles: int
) -> bool:
"""
執行一個交易循環(SOL -> USDC -> SOL)
Args:
wallet: 錢包實例
cycle_num: 當前循環編號
total_cycles: 總循環數
Returns:
循環成功返回 True,否則返回 False
"""
self.logger.log_cycle_start(wallet.address, cycle_num, total_cycles)
# Swap A: SOL -> USDC
self.logger.info(f"📤 Swap A: {self.config.swap_amount_sol} SOL -> USDC")
tx1_signature = await self.jupiter_client.swap_sol_to_usdc(
wallet=wallet,
sol_amount=self.config.swap_amount_sol,
sol_mint=self.config.sol_mint,
usdc_mint=self.config.usdc_mint,
)
if not tx1_signature:
self.logger.error("❌ Swap A 失敗")
self.logger.log_transaction(
wallet_address=wallet.address,
tx_type="SOL->USDC",
amount=self.config.swap_amount_sol,
token="SOL",
status="failed",
)
return False
self.logger.log_transaction(
wallet_address=wallet.address,
tx_type="SOL->USDC",
amount=self.config.swap_amount_sol,
token="SOL",
signature=tx1_signature,
status="success",
)
# 等待 5 秒讓 RPC 節點更新 USDC 餘額
await asyncio.sleep(5)
# 獲取 USDC 餘額
usdc_balance = await wallet.get_usdc_balance(
self.rpc_client, self.config.usdc_mint
)
if usdc_balance <= 0:
self.logger.error("❌ USDC 餘額為 0,Swap B 無法執行")
return False
# Swap B: USDC -> SOL
self.logger.info(f"📥 Swap B: {usdc_balance:.6f} USDC -> SOL")
tx2_signature = await self.jupiter_client.swap_usdc_to_sol(
wallet=wallet,
usdc_amount=usdc_balance,
sol_mint=self.config.sol_mint,
usdc_mint=self.config.usdc_mint,
)
if not tx2_signature:
self.logger.error("❌ Swap B 失敗")
self.logger.log_transaction(
wallet_address=wallet.address,
tx_type="USDC->SOL",
amount=usdc_balance,
token="USDC",
status="failed",
)
return False
self.logger.log_transaction(
wallet_address=wallet.address,
tx_type="USDC->SOL",
amount=usdc_balance,
token="USDC",
signature=tx2_signature,
status="success",
)
self.logger.log_cycle_complete(wallet.address, cycle_num, total_cycles)
return True
async def process_wallet(
self, wallet: Wallet, wallet_num: int, total_wallets: int
):
"""
處理單個錢包的所有循環
Args:
wallet: 錢包實例
wallet_num: 當前錢包編號
total_wallets: 總錢包數
"""
self.logger.log_wallet_start(wallet.address, wallet_num, total_wallets)
# 檢查餘額
if not await self.check_wallet_balance(wallet):
self.logger.error(f"❌ 錢包餘額不足,跳過此錢包")
return
wallet_success = 0
wallet_failed = 0
# 執行所有循環
for cycle in range(1, self.config.cycles_per_run + 1):
success = await self.execute_cycle(
wallet, cycle, self.config.cycles_per_run
)
if success:
wallet_success += 1
self.total_success += 1
else:
wallet_failed += 1
self.total_failed += 1
# 循環之間等待一段時間
if cycle < self.config.cycles_per_run:
await asyncio.sleep(5)
# 所有循環完成後,等待 20 秒再檢查一次是否有殘留 USDC
self.logger.info("\n⏰ 等待 20 秒後檢查是否有殘留 USDC...")
await asyncio.sleep(20)
# 檢查是否有殘留的 USDC
final_usdc_balance = await wallet.get_usdc_balance(
self.rpc_client, self.config.usdc_mint
)
if final_usdc_balance > 0:
self.logger.info(
f"💰 發現殘留 USDC: {final_usdc_balance:.6f} USDC,執行最終清理..."
)
# 執行最終的 USDC -> SOL 交換
final_signature = await self.jupiter_client.swap_usdc_to_sol(
wallet=wallet,
usdc_amount=final_usdc_balance,
sol_mint=self.config.sol_mint,
usdc_mint=self.config.usdc_mint,
)
if final_signature:
self.logger.info(f"✅ 最終清理成功")
self.logger.log_transaction(
wallet_address=wallet.address,
tx_type="USDC->SOL (清理)",
amount=final_usdc_balance,
token="USDC",
signature=final_signature,
status="success",
)
else:
self.logger.warning(f"⚠️ 最終清理失敗")
else:
self.logger.info("✅ 沒有殘留 USDC")
self.logger.log_wallet_complete(wallet.address, wallet_success, wallet_failed)
async def run_all_wallets(self):
"""執行所有錢包的交易循環"""
self.logger.info("\n" + "🚀" * 30)
self.logger.info("開始執行交易循環")
self.logger.info("🚀" * 30 + "\n")
total_wallets = len(self.wallet_manager)
for i, wallet in enumerate(self.wallet_manager, 1):
await self.process_wallet(wallet, i, total_wallets)
# 錢包之間等待一段時間
if i < total_wallets:
await asyncio.sleep(10)
# 打印總結
self.print_summary()
def print_summary(self):
"""打印執行總結"""
total_transactions = self.total_success + self.total_failed
success_rate = (
(self.total_success / total_transactions * 100) if total_transactions > 0 else 0
)
self.logger.info("\n" + "=" * 60)
self.logger.info("📊 執行總結")
self.logger.info("=" * 60)
self.logger.info(f"總交易數: {total_transactions}")
self.logger.info(f"成功: {self.total_success} ✅")
self.logger.info(f"失敗: {self.total_failed} ❌")
self.logger.info(f"成功率: {success_rate:.2f}%")
self.logger.info("=" * 60 + "\n")
async def close(self):
"""關閉客戶端連接"""
await self.rpc_client.close()
async def main():
"""主函數"""
try:
# 初始化日誌
init_logger()
logger = get_logger()
logger.info("🚀 啟動 Solana Volume Bot")
# 載入配置
try:
config = load_config()
validate_config(config)
print_config_summary(config)
except ConfigError as e:
logger.error(f"❌ 配置錯誤: {e}")
return 1
# 創建 Bot 實例
try:
bot = VolumeBot(config)
except WalletError as e:
logger.error(f"❌ 錢包初始化失敗: {e}")
return 1
# 詢問用戶是否開啟排程
enable_scheduler = get_user_choice()
if enable_scheduler:
# 開啟排程模式
logger.info("\n✅ 排程模式已啟用(每天台灣時間早上 09:00 執行)")
# 詢問是否立即執行一次
run_now = ask_run_immediately()
scheduler = BotScheduler()
# 添加任務
scheduler.add_job(bot.run_all_wallets, run_immediately=run_now)
# 保持運行
try:
await scheduler.run_forever()
except KeyboardInterrupt:
logger.info("\n⚠️ 收到停止信號")
finally:
scheduler.stop()
await bot.close()
else:
# 單次執行模式
logger.info("\n✅ 單次執行模式")
try:
await bot.run_all_wallets()
finally:
await bot.close()
logger.info("👋 程式已結束")
return 0
except KeyboardInterrupt:
logger.info("\n⚠️ 程式被用戶中斷")
return 130
except Exception as e:
logger.error(f"❌ 未預期的錯誤: {e}", exc_info=True)
return 1
if __name__ == "__main__":
try:
exit_code = asyncio.run(main())
sys.exit(exit_code)
except KeyboardInterrupt:
print("\n⚠️ 程式已停止")
sys.exit(130)