lushdog@outlook.com 1 сар өмнө
parent
commit
757a7ce793
1 өөрчлөгдсөн 20 нэмэгдсэн , 16 устгасан
  1. 20 16
      src/lib/jupiter.ts

+ 20 - 16
src/lib/jupiter.ts

@@ -4,7 +4,6 @@ import {
 	Keypair,
 	VersionedTransaction,
 } from '@solana/web3.js'
-import { getAssociatedTokenAddress } from '@solana/spl-token'
 import ky from 'ky'
 
 // USDC 和 USDT 作为默认的输入代币(用于兑换)
@@ -33,7 +32,7 @@ export interface JupiterSwapResponse {
 }
 
 /**
- * 获取代币余额
+ * 获取代币余额(汇总该 mint 在所有代币账户中的余额,不限于 ATA)
  */
 export async function getTokenBalance(
 	connection: Connection,
@@ -47,19 +46,22 @@ export async function getTokenBalance(
 			return balance / 1e9
 		}
 
-		// SPL Token 余额
-		const tokenAccount = await getAssociatedTokenAddress(
-			new PublicKey(mintAddress),
-			walletAddress
+		// SPL Token:用 getTokenAccountsByOwner 按 mint 筛选,汇总所有账户余额
+		// 避免只查 ATA 导致 pump 等代币在其它账户时被误判为 0
+		const accounts = await connection.getParsedTokenAccountsByOwner(
+			walletAddress,
+			{ mint: new PublicKey(mintAddress) }
 		)
 
-		try {
-			const accountInfo = await connection.getTokenAccountBalance(tokenAccount)
-			return accountInfo.value.uiAmount ?? 0
-		} catch {
-			// Token account 不存在,余额为 0
-			return 0
+		let total = 0
+		for (const item of accounts.value) {
+			const parsed = (item.account?.data as { parsed?: { info?: { tokenAmount?: { uiAmount?: number | null } } } })?.parsed
+			const ui = parsed?.info?.tokenAmount?.uiAmount
+			if (ui != null && typeof ui === 'number') {
+				total += ui
+			}
 		}
+		return total
 	} catch (error) {
 		console.error(`Error getting balance for ${mintAddress}:`, error)
 		return 0
@@ -162,17 +164,19 @@ export async function swapIfNeeded(
 ): Promise<{ success: boolean; txid?: string; error?: string }> {
 	const walletAddress = keypair.publicKey
 
-	// 检查当前余额
+	// 检查当前余额(按 mint 汇总所有代币账户,不限于 ATA)
 	const currentBalance = await getTokenBalance(
 		connection,
 		walletAddress,
 		outputMint
 	)
 
+	console.log(
+		`Balance check: current=${currentBalance.toFixed(6)}, required=${requiredAmount.toFixed(6)}`
+	)
+
 	if (currentBalance >= requiredAmount) {
-		console.log(
-			`Sufficient balance: ${currentBalance.toFixed(6)} >= ${requiredAmount.toFixed(6)}`
-		)
+		console.log(`Sufficient balance: ${currentBalance.toFixed(6)} >= ${requiredAmount.toFixed(6)}`)
 		return { success: true }
 	}